Android - 尝试从Fragment实现Adapter时出现NullPointerException

时间:2014-08-22 16:37:54

标签: android android-fragments implementation android-adapter baseadapter

我正在加载Fragment,而Fragment又创建了AdapterAdapter有一个interface。加载implements Adapter的片段。 我发起mCallback时没有错误。

以下是适配器中的代码:

Scanlist mScanlist; 
ScanlistListener mCallback;

public Scanadapter(Activity a, ArrayList<Scanmodel> d, Resources resLocal){
    mActivity = a;
    mData = d;
    res = resLocal;
    sInflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mScanlist = (Scanlist) mActivity.getFragmentManager().findFragmentById(R.layout.scanlist);
    try {
        mCallback = (ScanlistListener) mScanlist;
        Log.v(TAG, String.valueOf(mCallback)+ " here");
    } catch (ClassCastException e) {
        throw new ClassCastException(mScanlist.toString()
                + " must implement ScanlistListener");
    }
}

private class OnItemClickListener implements OnClickListener{
    private int mPosition;
    OnItemClickListener(int position){
        mPosition = position;
    }
    @Override
    public void onClick(View v) {
        mCallback.scanlistclick(v, mPosition);
    }
}

public interface ScanlistListener{
    public void scanlistclick(View v, int i);
}

点击列表中的某个项目即可获得NullPointerExceptiontry statement没有error exception启动mCallback变量。

08-22 10:19:09.099: E/AndroidRuntime(8112): java.lang.NullPointerException
08-22 10:19:09.099: E/AndroidRuntime(8112):     at net.xxxxx.adapter.Scanadapter$OnItemClickListener.onClick(Scanadapter.java:140)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at android.view.View.performClick(View.java:4489)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at android.view.View$PerformClick.run(View.java:18803)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at android.os.Handler.handleCallback(Handler.java:730)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at android.os.Looper.loop(Looper.java:137)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at android.app.ActivityThread.main(ActivityThread.java:5455)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at java.lang.reflect.Method.invoke(Method.java:525)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
08-22 10:19:09.099: E/AndroidRuntime(8112):     at dalvik.system.NativeStart.main(Native Method)

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果你的findFragmentByID找不到它正在寻找的布局元素,它将返回null。然后,您为mCallback分配null。使用强制转换分配null不会触发异常。也许使用调试器逐步执行代码,并确保找到您的视图并且mCallback未设置为null。