¿Excepción de puntero nulo en la vista de lista?

hie,I am trying to retrieve contacts name and their type .I want to put them in list view ,but getting null values at name and phone type array,as well as in list view.any help would be appreciable.thanks in advance.

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}

preguntado el 08 de noviembre de 11 a las 09:11

is R.id.listview in your main.xml layout? -

Please attach your stacktrace. -

yeah I have that in my xml file..<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/listview" android:cacheColorHint="#0000" /> </LinearLayout> -

what is stack trace.are you talking about log cat. -

Check the integer value you got in indexName and indexphonetype correctly..may be these value be empty so the value of cur.getString(indexName) value is null... please post your stacktrace to answer more.. -

4 Respuestas

movimiento

int i = 0;

outside the loop (before it)

respondido 08 nov., 11:13

yeah,that was the error I suppose.getting the list now but application getting force close as soon i run out of contacts while dragging down the list - love_bird

Inititalize the String array name and phoneType as below

  String[] name=new String[5];//5 is size of String array
  String[] phoneType=new String[5]; //5 is size of String array

respondido 08 nov., 11:14

intente usar:

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

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

EDIT: I just realized this is the same question as esta...

Puedes probar lo siguiente:

1) create a Class to represent 1 entry:

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;
}


}

Than in your code:

              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.


          }

contestado el 23 de mayo de 17 a las 15:05

I tried this but getting contact name in both the lines:Log.d("name",entry.getContactName()); Log.d("phoneType",entry.getPhoneType()); - love_bird

check your code if you use wrong set method, or wrong column index. I have tested this on my CallLogs phone database, and it get all data fields correctly. - hovanessyan

I need to ask one thing that do indexId,indexName and indexPhoneType,need to have one value because they are getting values 0,1,2 respectively at initialization.. - love_bird

those are the column index numbers (they should have different values), contained in your cursor. Those numbers mean that, the column containing your IDs, has index 0, column containing names, has index 1 and so on. - hovanessyan

any idea why setter and getter methods are running 20 times though I have only 10 contacts stored in my AVD..... - love_bird

    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. you forgot to initialize String arrays
  2. your count i isn't correct

respondido 08 nov., 11:14

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.