首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >疑惑如何在Android中查询联系人

疑惑如何在Android中查询联系人
EN

Stack Overflow用户
提问于 2011-08-03 20:57:24
回答 2查看 876关注 0票数 0

我正在制作一个使用联系人的Android应用程序。好消息是,我设法让它与Contacts.Phones一起工作,就像在许多教程中看到的那样。问题是Contacts.Phones已被弃用,并被ContactsContract所取代。我的应用程序需要从Android 1.5+开始工作。

我需要做一些简单的操作,如:-查询所有联系人-查询特定联系人-备份所有联系人

考虑到我需要让应用程序在所有版本的android上运行,那么实现这一目标的最佳方法是什么?我是否需要在手机上检查当前的api级别,并且有两个代码块,一个在api 5之前?

EN

Stack Overflow用户

回答已采纳

发布于 2011-08-03 21:24:50

这是一个可选的解决方案

代码语言:javascript
运行
复制
int apiVersion = android.os.Build.VERSION.SDK_INT;

    if(apiVersion < 5) {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(People.CONTENT_URI, 
            null, null, null, null);
        if (cur.getCount() > 0) {
         while (cur.moveToNext()) {
             String id = cur.getString(cur.getColumnIndex(People._ID));
             String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
         }
        }
    } else {
        String columns[] = new String[]{ ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };       
        Cursor  cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                        columns,                
                        null,               
                        null,               
                        ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
        if (cursor.getCount() > 0) {
             while (cursor.moveToNext()) {
                long id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));   
                String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();

             }
        }
    }

这里有一个使应用程序Supporting the old and new APIs in the same application的教程,这一定会对你有所帮助。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6926785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档