In my Android application, I have a fragment activity which it has a progressbar. This progress bar set to visible when any fragment invoke the interface. Therefore, the code for fragment class is like this:
public class MainScreen extends FragmentActivity {
public interface OnConnectingToInternet {
public void showProgressbar(boolean flag);
}
// rest of codes
.
.
.
// Implementing Interface
public void showProgressbar(boolean flag) {
if(flag){
myProgressbar.showProgressBar();
} else {
myProgressbar.hideProgressBar();
}
}
}
Each fragment should connect to Internet and get data, however before that they should invoke interface. I have written following code for one class (the code for other fragments is like this).
public class TopRecipesFragment extends Fragment {
private OnConnectingToInternet onConnectingToInternet;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// onConnectingToInternet = (OnConnectingToInternet) 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 I don't know how to instantiate this interface. If I don't put onConnectingToInternet = (OnConnectingToInternet) activity;
, then, after running application, it will crash in a NullPointerException
.
But, if I instantiate like that, then application crashes because of casting problem. I cannot instantiate it in normal way either, like onConnectingToInternet = new MainScreen();
.
What is the solution? Any suggestion would be appreciated. Thanks