列表视图中的空指针异常?

Posted

技术标签:

【中文标题】列表视图中的空指针异常?【英文标题】:null pointer exception in list view? 【发布时间】:2011-12-24 07:23:00 【问题描述】:

你好,我正在尝试检索联系人姓名及其类型。我想将它们放在列表视图中,但在名称和电话类型数组以及列表视图中获取空值。任何帮助都会很重要。谢谢提前。

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 ComponentInfoapplication.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 HistoryRecord44f48960 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 HistoryRecord44f48960 application.test/.TestActivity

【问题讨论】:

在你的 main.xml 布局中是 R.id.listview 吗? 请附上您的堆栈跟踪。 是的,我的 xml 文件中有这个。schemas.android.com/apk/res/android" android:orientation= "垂直" android:layout_ android:layout_> 什么是堆栈跟踪。你在说日志猫吗。 正确检查您在 indexName 和 indexphonetype 中获得的整数值。这些值可能为空,因此 cur.getString(indexName) 值为空...请发布您的堆栈跟踪以回答更多.. 【参考方案1】:

移动

int i = 0;

在循环之外(在它之前)

【讨论】:

是的,那是我想的错误。现在获取列表,但是当我在下拉列表时用完联系人时,应用程序会强制关闭【参考方案2】:

如下初始化String数组名和phoneType

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

【讨论】:

【参考方案3】:

尝试使用:

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

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

编辑:我刚刚意识到这与this one...

您可以尝试以下方法:

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.


          

【讨论】:

我试过了,但在这两行中都获取了联系人姓名:Log.d("name",entry.getContactName()); Log.d("phoneType",entry.getPhoneType()); 如果您使用了错误的设置方法或错误的列索引,请检查您的代码。我已经在我的 CallLogs 电话数据库上对此进行了测试,它正确地获取了所有数据字段。 我需要问一件事,做 indexId、indexName 和 indexPhoneType,需要有一个值,因为它们在初始化时分别获取值 0,1,2.. 这些是包含在光标中的列索引号(它们应该具有不同的值)。这些数字意味着,包含您的 ID 的列的索引为 0,包含名称的列的索引为 1,依此类推。 知道为什么 setter 和 getter 方法运行 20 次,尽管我的 AVD 中只存储了 10 个联系人.....【参考方案4】:
    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
    您忘记初始化字符串数组 你的计数不正确

【讨论】:

以上是关于列表视图中的空指针异常?的主要内容,如果未能解决你的问题,请参考以下文章

java中的空指针异常怎么解决

onPostExecute 中的空指针异常

操作栏中的空指针异常[重复]

在检查空值时 onPostExecute 中的 AsyncTask 中的空指针异常

片段中的空指针异常

java servlet中的空指针异常[关闭]