Исключение нулевого указателя в виде списка?

Я пытаюсь получить имя контакта и его тип. Я хочу разместить их в виде списка, но получить нулевые значения в имени и в массиве типов телефонов, а также в виде списка. Любая помощь будет заметна. Заранее спасибо.

package application.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;  
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public final class TestActivity extends Activity {
String[] name;
String[] phoneType;
ListView lv;
String s[];

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);        

   testGetContacts();

   lv = (ListView)findViewById(R.id.listview);
        ArrayAdapter<String> sa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,s);
        lv.setAdapter(sa);

}//method

private void testGetContacts()  { 

    ContentResolver cr = getContentResolver();    
    String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE};     
    Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                projection, null, null, null);     

    if (cur != null && cur.moveToFirst()) { 

        try {

            int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
            int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
             int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

          name=new String[cur.getCount()];

         phoneType=new String[cur.getCount()];


         while (cur.moveToNext()) {

               int  i=0;
               String id = cur.getString(indexID);    
     null-->    name[i] = cur.getString(indexName);  
     null-->     phoneType[i] =  cur.getString(indexPhoneType);       

              String temp="id="+id+"-name="+name[i]+"-phoneType="+phoneType[i];
              s[i]=temp;
              i++;
}//while
        }catch(Exception e){

e.printStackTrace();    
    }//catch
}//if
}//method}
}   

Logcat:

11-08 15:21:45.250: WARN/System.err(1049): java.lang.NullPointerException
11-08 15:21:45.250: WARN/System.err(1049):     at application.test.TestActivity.testGetContacts(TestActivity.java:60)
11-08 15:21:45.270: WARN/System.err(1049):     at application.test.TestActivity.onCreate(TestActivity.java:23)
11-08 15:21:45.270: WARN/System.err(1049):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-08 15:21:45.270: WARN/System.err(1049):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-08 15:21:45.270: WARN/System.err(1049):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-08 15:21:45.270: WARN/System.err(1049):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-08 15:21:45.270: WARN/System.err(1049):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-08 15:21:45.279: WARN/System.err(1049):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-08 15:21:45.290: WARN/System.err(1049):     at android.os.Looper.loop(Looper.java:123)
11-08 15:21:45.290: WARN/System.err(1049):     at android.app.ActivityThread.main(ActivityThread.java:4627)
11-08 15:21:45.290: WARN/System.err(1049):     at java.lang.reflect.Method.invokeNative(Native Method)
11-08 15:21:45.290: WARN/System.err(1049):     at java.lang.reflect.Method.invoke(Method.java:521)
11-08 15:21:45.290: WARN/System.err(1049):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-08 15:21:45.290: WARN/System.err(1049):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-08 15:21:45.300: WARN/System.err(1049):     at dalvik.system.NativeStart.main(Native Method)
11-08 15:21:45.300: DEBUG/AndroidRuntime(1049): Shutting down VM
11-08 15:21:45.300: WARN/dalvikvm(1049): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049): FATAL EXCEPTION: main
11-08 15:21:45.349: ERROR/AndroidRuntime(1049): java.lang.RuntimeException: Unable to start activity ComponentInfo{application.test/application.test.TestActivity}: java.lang.NullPointerException
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.os.Looper.loop(Looper.java:123)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.ActivityThread.main(ActivityThread.java:4627)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at java.lang.reflect.Method.invokeNative(Native Method)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at java.lang.reflect.Method.invoke(Method.java:521)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at dalvik.system.NativeStart.main(Native Method)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049): Caused by: java.lang.NullPointerException
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at java.util.Arrays$ArrayList.<init>(Arrays.java:49)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at java.util.Arrays.asList(Arrays.java:171)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:125)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at application.test.TestActivity.onCreate(TestActivity.java:26)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-08 15:21:45.349: ERROR/AndroidRuntime(1049):     ... 11 more
11-08 15:21:45.380: WARN/ActivityManager(58):   Force finishing activity application.test/.TestActivity
11-08 15:21:45.911: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{44f48960 application.test/.TestActivity}
11-08 15:21:47.029: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
11-08 15:21:56.575: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{44f48960 application.test/.TestActivity}

4 ответа

Инициализируйте имя массива String и phoneType, как показано ниже

  String[] name=new String[5];//5 is size of String array
  String[] phoneType=new String[5]; //5 is size of String array
    private void testGetContacts() {

    ContentResolver cr = getContentResolver();
    String[] projection = new String[] { ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE };
    Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI, projection,
            null, null, null);

    if (cur != null && cur.moveToFirst()) {

        try {

            int indexID = cur
                    .getColumnIndexOrThrow(ContactsContract.Contacts._ID);
            int indexName = cur
                    .getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
            int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);
            int count = cur.getCount();

            name = new String[count];
            phoneType = new String[count];
            s = new String[count];

            int i = 0;
            while (cur.moveToNext()) {

                String id = cur.getString(indexID);
                name[i] = cur.getString(indexName);
                phoneType[i] = cur.getString(indexPhoneType);
                String temp = "id=" + id + "-name=" + name[i]
                        + "-phoneType=" + phoneType[i];
                s[i] = temp;
                i = i + 1;
            }// while
        } catch (Exception e) {

            e.printStackTrace();
        }// catch
    }// if
}// method}
  1. вы забыли инициализировать строковые массивы
  2. ваш счет я не прав

Переехать

int i = 0;

вне цикла (до него)

Попробуйте использовать:

        String[] projection = new String[] { Data._ID,
            ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE}; 

      Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
            projection, null, null, null); 

РЕДАКТИРОВАТЬ: Я только что понял, что это тот же вопрос, что и этот...

Вы можете попробовать следующее:

1) создать класс для представления 1 записи:

public class ContactsEntry {

String contactId;
String contactName;
String phoneType;
public String getContactId() {
    return contactId;
}
public void setContactId(String contactId) {
    this.contactId = contactId;
}
public String getContactName() {
    return contactName;
}
public void setContactName(String contactName) {
    this.contactName = contactName;
}
public String getPhoneType() {
    return phoneType;
}
public void setPhoneType(String phoneType) {
    this.phoneType = phoneType;
}


}

Чем в вашем коде:

              while (cur.moveToNext()) {

              String id = cur.getString(indexID);    
              String name = cur.getString(indexName);  
              String phoneType =  cur.getString(indexPhoneType);

              ContactsEntry entry = new ContactsEntry();
              entry.setContactId(id);
              entry.setContactName(name);
              entry.setPhoneType(phoneType);

               //// do some logging or whatever.


          }
Другие вопросы по тегам