In my Android app, I have fragment activity that has a progress indicator. This progress bar is shown on the display when any fragment calls the interface. Therefore, the code for the fragment class is as follows:
public class MainScreen extends FragmentActivity {
public interface OnConnectingToInternet {
public void showProgressbar(boolean flag);
}
.
.
.
public void showProgressbar(boolean flag) {
if(flag){
myProgressbar.showProgressBar();
} else {
myProgressbar.hideProgressBar();
}
}
}
Each fragment must connect to the Internet and receive data, but before that, they must call the interface. I wrote the following code for one class (code for other fragments is similar to this).
public class TopRecipesFragment extends Fragment {
private OnConnectingToInternet onConnectingToInternet;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i(TAG, "Fragment attached to activity.");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
New MyAsyncTask.execute();
}
public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
Log.i(TAG, "myAsyncTask is about to start...");
onConnectingToInternet.showProgressbar(true);
}
@Override
protected Boolean doInBackground(Void... params) {
...
}
@Override
protected void onPostExecute(Boolean result) {
Log.i(TAG, "myAsyncTask is about to start...");
onConnectingToInternet.showProgressbar(false);
}
}
The problem is that I do not know how to instantiate this interface. If I don’t install it onConnectingToInternet = (OnConnectingToInternet) activity;, then after launching the application it will be split into NullPointerException.
, , - . , onConnectingToInternet = new MainScreen();.
? .