IceJOKER IceJOKER - 6 months ago 38
Android Question

Sometimes fragment lose activity

I can't to understand what's wrong, on my device app working nice, but sometimes in log(app users,sessions, crashes ... tracking via some service) i see app crash(NullPointerException), Toast cann't be run because activity variable is null.

Line 45 (populateCats() method throws exception NullPointerException)


import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.ArrayList;

public class CatsList extends ListFragment implements OnTaskCompleted {
Document doc;
MainActivity activity;
ArrayList<Cat> cats;

public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cat cat = cats.get(position);


public void onCreate(Bundle savedInstanceState) {
new GetData(activity, this, false).execute(Jsoup.connect(MainActivity.url));

public void onAttach(Activity activity) {
this.activity = (MainActivity) activity;

public void populateCats(){
if(doc == null)

Toast.makeText(activity, "Error....", Toast.LENGTH_SHORT).show();
Toast.makeText(activity, "Success....", Toast.LENGTH_SHORT).show();




at android.widget.Toast.<init>(
at android.widget.Toast.makeText(
at PACKAGE_NAME.CatsList.populateCats(
at PACKAGE_NAME.CatsList.taskCompleted(
at PACKAGE_NAME.GetData.onPostExecute(
at PACKAGE_NAME.GetData.onPostExecute(
at android.os.AsyncTask.finish(
at android.os.AsyncTask.access$600(
at android.os.AsyncTask$InternalHandler.handleMessage(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(
at dalvik.system.NativeStart.main(Native Method)

AndroidManifect.xml also contain- android:configChanges="keyboardHidden|orientation|screenSize"

Answer Source

If I've assumed correctly, the method populateCats() is called asynchronously by the GetData class. This means that there are several interleaving where the asynchronous procedure is still running when the user close the activity. This will cause a NPE because, if you have implemented the onAttach/onDetach correctly, you are clearing the activity reference when the fragment is detached after the activity is closed.

As a good practice, you should always check the state of every Activity reference or getActivity() invocation and verify that they are not null before execute any other instruction.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download