I have an application that has an Asynctask
for web Api Requests and and there are many request for many tabs.
When user scrolls very fast between tabs many request lunches! but when user closes the activity, some ongoing do in background causes app crashes.
I tried this: in my doinBackground I always check if fragment isAdded()
@Override
protected Void doInBackground(Void... Params) {
Bundle bundle = getArguments();
String url = ServiceHandler.serverEnum.serverRootPath + ServiceHandler.serverEnum.Me.toString();
if(isAdded()){
response = StaticUtils.generateReguest(mContext, url, headerParams, bodyParams, URLParams, null, ServiceHandler.serviceMethod.get.toString());
}
return null;
}
I also do this when Asynctask runs from Activity:
onStop of activity I canceled the ran Asyctask then onPostExecute
of it check if not canceled do some UI stuff. but problem is I get crash in doInBackground
.
this is the line that crash happens in creating respond in StaticUtils.generateReguest
:
if (status != 200 && status != 401 && status != 404 && status != 0) {
Intent intent = new Intent(context, ErrorActivity.class); //error point to this line
intent.putExtra(ErrorActivity.REASON, "SERVER");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
(context).startActivity(intent);
}
and this is log cat that lead to above line:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
I think it may because of context. cause when I generate a request I pass Activity context to Requestgenerator and some time as you see in code it lead to show error activity. when user closese the activity context changed so Request generator can not open `ErrorActivity. what is best practice to handle this? I googled and could not find a good solution?