gpt4 book ai didi

android - 如何从联系人数据库中读取所有联系人并将其存储到列表中?

转载 作者:行者123 更新时间:2023-11-29 14:54:13 27 4
gpt4 key购买 nike

我正在尝试从联系人表中读取联系人并将它们全部存储到列表变量中..但无法弄清楚为什么它似乎不起作用..在执行时强制关闭。需要联系人通过 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());
}

list 文件有2个权限

     <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>

和用于将 sqlitopenhelper 扩展到 getWritableDatabase 的 DBHelper 类..

    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
}

最佳答案

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());
}

使用上面的代码从联系人数据库中获取姓名和号码列表。

关于android - 如何从联系人数据库中读取所有联系人并将其存储到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com