空指针异常

时间:2012-12-28 19:37:11

标签: java android

我正在尝试从手机中的联系人中选择显示名称,手机号码,并使用列表视图在列表中显示这些号码。但是在运行以下代码时我得到空指针异常:

public class SeeActivity extends ListActivity {
    public String [] allname;
       public String [] allnumber;
       public int listcount=0;
       public String [] details;
       String[] PROJECTION = new String[] {
               ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
               ContactsContract.CommonDataKinds.Phone.NUMBER




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


;

        Cursor phone= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,PROJECTION ,null ,null ,null);

       try{
        while(phone.moveToNext())
        {  

           String name= phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
           String number=phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
           allname[listcount]=name;
           allnumber[listcount]=number;
           details [listcount]=name+"    "+number;
           listcount=listcount+1;

        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,details);
        setListAdapter(adapter);
        ListView l=getListView();
           l.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                Toast.makeText(getApplicationContext(),((TextView)arg1).getText() , Toast.LENGTH_SHORT).show();



           }
        });}
       catch( Exception e)
       {
           Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();   
       }



    }


}

2 个答案:

答案 0 :(得分:1)

问题是你已经声明了String数组,但是你没有为它们创建/分配内存:

public String [] allname;
public String [] allnumber;
public int listcount=0;
public String [] details;

因此,当您尝试访问它们时:

allname[listcount]=name;
allnumber[listcount]=number;
details [listcount]=name+" "+number;

它给出了空指针异常。因此,在声明它们时创建String数组:

public String[] allname = new String[100];
public String[] allnumber = new String[100];
public int listcount = 0;
public String[] details = new String[100];

查看arrays


不要忘记关闭光标。

答案 1 :(得分:0)

    public String [] allname;
    public String [] allnumber;

指向null;以及分配结果NullPointerException

       allname[listcount]=name;
       allnumber[listcount]=number;

更改数组创建语句,如:

public String[] allname = new String[10];
public String[] allnumber = new String[10];

如果你不提前知道尺寸,我会建议使用像ArrayList这样的东西而不是数组。