我有一个片段视图,检查互联网连接代码。在showSnack函数的else部分中获取错误如下。
错误:尝试调用虚方法' android.content.Context android.view.ViewGroup.getContext()'在空对象引用上
以下是我的代码
public class LatestNews extends Fragment implements SwipeRefreshLayout.OnRefreshListener, ConnectivityReceiver.ConnectivityReceiverListener {
//declare variables
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_view,container,false);
// Manually checking internet connection
checkConnection();
return v;
});
private void checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
private void showSnack(boolean isConnected) {
String message;
int color;
if (isConnected) {
new DownloadJSON().execute();
} else {
swipeRefreshLayout.setRefreshing(false);
mProgressBar.setVisibility(View.GONE);
message = "Sorry! Not connected to internet";
color = Color.RED;
Snackbar snackbar = Snackbar.make(getActivity().findViewById(R.id.fab), message, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(color);
snackbar.show();
}
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}