public class ContactInfoParser extends Activity {
ListView mListView;
List<String> contactList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListView = (ListView) findViewById(R.id.list_contact);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactList);
mListView.setAdapter(adapter);
readContacts();
}
private void readContacts() {
Cursor cursor = null;
try{
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String displayname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String diplaynumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(displayname + "\n" + diplaynumber);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (cursor != null) {
cursor.close();
}
}
}
}
上面这段代码从其他activity跳转过来,执行到mListView.setAdapter(adapter);这句话的时候,提示一直报错空指针异常。
报错代码如下:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.liujing.shanzhaisafe/com.liujing.shanzhaisage.fangdaomokuai.dialog.ContactInfoParser}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.liujing.shanzhaisage.fangdaomokuai.dialog.ContactInfoParser.onCreate(ContactInfoParser.java:24)