我试图从联系人表中读取联系人并将所有联系人存储到列表变量中...但是无法弄清楚为什么它似乎无法正常工作......在执行时关闭一个强制关闭。需要联系人通过json对象发送到Web服务器。
private static final String TABLE_CONTACTS = "contacts";
// contacts JSONArray
JSONArray contacts = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<contact> l=new ArrayList<contact>();
String query="SELECT * FROM"+ TABLE_CONTACTS;
DBHelper help= new DBHelper(getBaseContext());
SQLiteDatabase db=help.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst())
{
do{
contact contact = new contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
Toast.makeText(this,contact.name,Toast.LENGTH_LONG);
l.add(contact);
}
while(cursor.moveToNext());
}
和清单文件有2个权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
和DBHelper类,用于将sqlitopenhelper扩展为getWritableDatabase ..
class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
DBHelper(Context context) {
super(context,DATABASE_NAME, null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:5)
private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
使用上面的代码从联系人数据库中获取姓名和号码列表。
答案 1 :(得分:1)