我能够获取名称,但在尝试检索名称及其类型时,我得到NULLPOINTEREXCEPTION
,并在name[i]
,phoneType[i]
中返回空值,并在列表视图中。
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.provider.ContactsContract.Contacts.Data;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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.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[] { 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()];
while (cur.moveToNext()) {
int i=1;
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
}catch(Exception e){
e.printStackTrace();
}//catch
}//if
}//method
}//class
...................................................................
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://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>