获取空指针异常?

时间:2011-11-07 13:01:33

标签: android nullpointerexception

我试图将一个数组中的联系人名称和他们的类型放在另一个数组中,但是无法通过空指针异常进行处理。这是我的代码。我已经指出了我得到空指针异常的行。请帮助..谢谢。

package application.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;  
import android.provider.ContactsContract.Contacts.Data;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

public final class TestActivity extends Activity {
String[] name;
String[] phoneType;
ListView lv;
ListViewAdapter lva;


    public static final String TAG = "ContactManager";
@Override
public void onCreate(Bundle savedInstanceState)
{
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);        
    LinearLayout mainLayout=new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);               
    LayoutInflater layoutInflater = getLayoutInflater();        
    mainLayout.addView(layoutInflater.inflate(R.layout.main,null));
    mainLayout.addView(layoutInflater.inflate(R.layout.extra,null));

    this.addContentView(mainLayout, params);

      lv = (ListView)findViewById(android.R.id.list);
     lva = new ListViewAdapter(this,name,phoneType); 
    lv.setAdapter(lva);
    testGetContacts();
}


private void testGetContacts() { 

        ContentResolver cr = getContentResolver();

        String[] projection = new String[] { Data._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);

          while (cur.moveToNext()) {
             int  i=1;
              String id = cur.getString(indexID);    
 //HERE LIES NULL POINTER EXCEPTION   name[i] = cur.getString(indexName);  
 //HERE TOO              phoneType[i] =  cur.getString(indexPhoneType);

             i++;


              System.out.println(id + "\n");
              System.out.println(name + "\n");
              System.out.println(phoneType + "\n");


          }


        } catch (SQLException sqle) {
           //handling exception       
        } finally { 
         if (!cur.isClosed()) {
             cur.close();
         }     
     }

        }

}
}

5 个答案:

答案 0 :(得分:1)

您没有初始化String []名称,因此当您尝试访问它时,会得到空指针异常。我建议使用更有意义的变量名。 '名字'非常模棱两可。

答案 1 :(得分:1)

您的姓名和电话号码尚未初始化。

String[] name = new String[EXPECTED_SIZE];
String[] phoneType = new String[EXPECTED_SIZE];

在尝试运行之前,任何正确的IDE都应该告诉您。您使用的是Eclipse还是IntelliJ?你应该!

答案 2 :(得分:0)

在使用之前初始化String[]名称。 你可以这样做:

name=new String[cur.getCount()];
String s="";
while (cur.moveToNext()) {

     int  i=1;
     String id = cur.getString(indexID);    
     name[i] = cur.getString(indexName);  
     phoneType[i] =  cur.getString(indexPhoneType);         

     //System.out.println(id + "\n");
     //System.out.println(name + "\n");
     //System.out.println(phoneType + "\n");

     s=s+"id="+id+" name="+name[i]+" phoneType="+phoneType[i]+"\n";
     i++;
}
Toast.makeText(getApplicationContext(),i+" - "+s).show();

修改:

在布局文件夹中创建一个xml文件。

<强> main.xml中

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical" >    

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listview"
        android:cacheColorHint="#0000"
        />
</LinearLayout>

现在位于 TestActivity.class

public final class TestActivity extends Activity {

String[] name;
String[] phoneType;
ListView lv;
String s[];
public static final String TAG = "ContactManager";

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

    testGetContacts();

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


private void testGetContacts() { 

    ContentResolver cr = getContentResolver();    
    String[] projection = new String[] { Data._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()];
          s=new String[cur.getCount()];

          while (cur.moveToNext()) {

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


              String temp="id="+id+"-name="+name[i-1]+"-phoneType="+phoneType[i-1];
              s[i-1]=temp;
              i++;
}    

}

答案 3 :(得分:0)

您正在获取空指针,因为您正在访问错误的索引。

试试这个:

s=new String[cur.getCount()];
int  i=1;
while (cur.moveToNext()) {    

                   String id = cur.getString(indexID);    
                   name[i-1] = cur.getString(indexName);  
                   phoneType[i-1] =  cur.getString(indexPhoneType);       


                  String temp="id="+id+"-name="+name[i-1]+"-phoneType="+phoneType[i-1];
                  s[i-1]=temp;
                  i++;
    }

以及lv=(ListView)findViewById(R.id.listview);代替lv=(ListView)findViewById(android.R.id.list);

你应该在这里添加一个条件:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);      
       testGetContacts();

if(s.length()>0)
{
    lv = (ListView)findViewById(R.id.listview);
    ArrayAdapter<String> sa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,s);
    lv.setAdapter(sa);
}
else
{
   Toast.makeText(getApplicationContext(),"Nothing Found",Toast.LENGTH_SHORT).show();
}

答案 4 :(得分:0)

试试这个并告诉我它有所帮助:

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

            lv = (ListView)findViewById(R.id.listview);
            testGetContacts();
            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[] { Data._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()];
                  s=new String[cur.getCount()];
                  int  i=1;
                  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-1]=temp;
                      i++;                  
                   }//while
             ArrayAdapter<String> sa=new ArrayAdapter<String>(getApplicationContext(),               android.R.layout.simple_list_item_1,s);
             lv.setAdapter(sa);
             }catch(Exception e){

        e.printStackTrace();    
            }//catch

            }//if

        }//method