有时碎片失去活动

时间:2015-01-01 17:04:25

标签: android android-fragments

我无法理解什么是错的,在我的设备应用程序上运行良好,但有时在日志中(应用程序用户,会话,崩溃...通过某些服务跟踪)我看到应用程序崩溃(NullPointerException),Toast不能因为活动变量为空而被运行。

第45行( populateCats()方法抛出异常NullPointerException

    package package.name;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
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;

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

        //SOME CODE
    }

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

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (MainActivity) activity;
    }

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

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

        //SOME CODE
    }


}

日志:

java.lang.NullPointerException
at android.widget.Toast.<init>(Toast.java:98)
at android.widget.Toast.makeText(Toast.java:254)
at PACKAGE_NAME.CatsList.populateCats(CatsList.java:64)
at PACKAGE_NAME.CatsList.taskCompleted(CatsList.java:92)
at PACKAGE_NAME.GetData.onPostExecute(GetData.java:61)
at PACKAGE_NAME.GetData.onPostExecute(GetData.java:12)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)

AndroidManifect.xml还包含 - android:configChanges =“keyboardHidden | orientation | screenSize”

1 个答案:

答案 0 :(得分:5)

如果我假设正确, GetData 类会异步调用 populateCats()方法。这意味着有几个交错存在,当用户关闭活动时,异步过程仍在运行。这将导致NPE,因为如果您已正确实现onAttach / onDetach,则在活动关闭后分离片段时,您将清除活动引用。

作为一种好的做法,您应该始终检查每个Activity引用或getActivity()调用的状态,并在执行任何其他指令之前验证它们是否为null。