片段中的NPE ListView

时间:2014-11-20 10:04:47

标签: android android-fragments android-listview

在将我的活动转换为碎片后,我一直有问题。

这里我试图获取SQLite数据,并将其加载到listView ..在Activity中它工作得很好!

现在我在lv.setAdapter(adapter);

获得NPE
    dbcon = new SQLController(getActivity());
    dbcon.open();
    addmem_bt = (Button) v.findViewById(R.id.add_bt_id);
    lv = (ListView) v.findViewById(R.id.memberList_id);
    // onClickListiner for addmember Button
    // Attach The Data From DataBase Into ListView Using Crusor Adapter
    Cursor cursor = dbcon.readData();
    String[] from = new String[]{DBhelper.MEMBER_ID, DBhelper.MEMBER_NAME};
    int[] to = new int[]{R.id.member_id, R.id.member_name};

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(
            getActivity(), R.layout.view_member_entry, cursor, from, to);

    adapter.notifyDataSetChanged();
    lv.setAdapter(adapter);

我也有一个logcat:

11-20 10:58:24.315    6539-6539/android.nl.hbbaa.bloodooa E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.hbbaa.startingpoint.nl.SQL.bababodFragment.onCreateView(bababodFragment.java:56)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:450)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)

THX

1 个答案:

答案 0 :(得分:0)

尝试使用lv = (ListView) getActivity().findViewById(R.id.memberList_id);代替lv = (ListView) v.findViewById(R.id.memberList_id);您的ListView是活动UI的成员,而不是片段。