solution for AsyncTask.onPostExecute throws NullPointerException when fragment's view was destroyed in android
like title, there is the issue like example:
public class TestFragment extends Fragment {
private boolean isDestroyed = false;
private TextView mTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.simple_list_item_1, null);
mTextView = (TextView) view.findViewById(R.id.text1);
return view;
}
class FetchNewsTask extends AsyncTask {
@Override
protected void onPreExecute() {
// show ProgressBar here
}
@Override
protected String doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}
}
that is a very simple fragment in a program, but there have a bug if you do that.
AsyncTask well execute in another thread, but view is destroyed this thread maybe not executed, then it throws a nullpoint exception, so this is the issue.
I find a very simpleness solution for this issue, like this
public class TestFragment extends Fragment {
private boolean isDestroyed = false;
private TextView mTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.simple_list_item_1, null);
mTextView = (TextView) view.findViewById(R.id.text1);
return view;
}
class FetchNewsTask extends AsyncTask {
@Override
protected void onPreExecute() {
// show ProgressBar here
}
@Override
protected String doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(String result) {
// when task executed the text view text well change,
// but when this task return after this fragment changed, it must throws a NullPointerException
if (isDestroyed) return;
mTextView.setText(result);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// I set a flag here for this fragment's view was destroyed
isDestroyed = true;
}
}
now you app can not crash when you replace fragment that task has not return.
Thx sir, this code Insya Allah run fluently :)
回复删除Thanks dude, I have been struggling for 8 days but to no avail. Cheers
回复删除you can seed me email with your code. and I can help you if I can .
删除jerry.jobs[at]qq.com replace [at] to '@'.
删除謝謝!!問題解決了!!
回复删除Hi sir,i dont use fragments, instead i used sockets,but it is throwing this exception..can u help me
回复删除show me your code. send to "jerry.jobs#qq.com" replace '#' to '@'.
删除hi. good afternoon. im having a problem with my asynctask can you help me? thank you very much
回复删除