使用Fragment检索联系人列表时出现NullPointerException

时间:2016-06-29 09:52:26

标签: android listview android-fragments android-listfragment

我想使用Fragment显示联系人列表。当我将Adapter设置为列表视图时,程序崩溃。

06-29 14:34:06.836: E/AndroidRuntime(14444): FATAL EXCEPTION: main
06-29 14:34:06.836: E/AndroidRuntime(14444): Process: com., PID: 14444
06-29 14:34:06.836: E/AndroidRuntime(14444): java.lang.NullPointerException
06-29 14:34:06.836: E/AndroidRuntime(14444):    at Fragments.ContactsFragment.onCreateView(ContactsFragment.java:185)
06-29 14:34:06.836: E/AndroidRuntime(14444):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
06-29 14:34:06.836: E/AndroidRuntime(14444):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
06-29 14:34:06.836: E/AndroidRuntime(14444):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
06-29 14:34:06.836: E/AndroidRuntime(14444):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
06-29 14:34:06.836: E/AndroidRuntime(14444):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
06-29 14:34:06.836: E/AndroidRuntime(14444):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)

以下是代码

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
         view = inflater.inflate(R.layout.fragment_view, container, false);

         lvContact = (ListView) view.findViewById(R.id.list);


     final ArrayList<String> list = new ArrayList<String>();
        ArrayAdapter<String> adapter;


        Cursor cursor = getActivity(). getContentResolver().query(   ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null); 

        while (cursor.moveToNext()) 
        {
             name =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
             phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


        sb.append("\n " + phoneNumber +" \n");
        String sValues = sb.toString();

        adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, list);
        lvContact.setAdapter(adapter); 

         list.add(sValues);
         sb.setLength(0);
     }


        lvContact.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    int position, long id) {

                 String item = list.get(position);

                Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();

                return true;
            }
        });

    return view;

}

0 个答案:

没有答案