【问题标题】:Android. to display contacts as list view安卓。将联系人显示为列表视图
【发布时间】:2011-05-24 13:50:35
【问题描述】:

我想在列表视图中显示联系人并对所有联系人添加操作,例如单击特定联系人应显示电话号码、邮件 ID 和特定联系人的删除...

import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CPDemo1 extends ListActivity {


    @SuppressWarnings("unchecked")
 public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
     String str[]=    {"datta","vivek","Nagesh sir","shiv"};
     String name; 

        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);

        if (cursor.moveToFirst())


         do {

         int x = 0;

         name = cursor.getString(nameIdx);
         str[x]= name;
                 x++;
          ArrayAdapter arr = new ArrayAdapter(this, android.R.layout.simple_list_item_1,str);

          setListAdapter(arr);
 } while(cursor.moveToNext());

        }

【问题讨论】:

  • 是什么阻碍了你做你想做的事?
  • @WarrenFaith ...我正在尝试显示电话簿联系人,但我无法这样做...在我的代码中,name 变量仅通过电话中的一个联系人覆盖了核心值书..我想首先在列表视图中显示所有联系人,然后在其上添加操作..看看我在哪里缺少循环来做到这一点..

标签: android listview android-contacts listactivity


【解决方案1】:

您当前代码中的问题是为每个循环创建新适配器。只需将ArrayAdapter arr = new ArrayAdapter(this, android.R.layout.simple_list_item_1,str); 移出do while loop。还有一个问题,你在UIThread 上工作太多(循环光标),所以如果你的联系人数量很大,用户会看到黑屏或 ANR。学会使用AsyncQueryHandlerCursorAdapter,都在我的链接和nikki的链接里

为什么不看看 Android 源代码中的默认联系人应用程序: 下面是我的自定义联系人应用程序。

https://github.com/android/platform_packages_apps_contacts

【讨论】:

  • 要否决我的答案,您应该留下一个理由。对于这样的一般问题,不要指望复制粘贴运行 sn-p。我的回答帮助他改进了他提供的代码。
【解决方案2】:

只需看看下面的链接,并尝试使用此代码将保存在 android 电话簿中的联系人显示到您的应用程序中。

http://developer.android.com/resources/samples/ContactManager/index.html

【讨论】:

    【解决方案3】:

    这里对你发布的代码稍作改动,它会解决你的问题。

    if (cursor.moveToFirst())
        {
    
            int x = 0;
         do {
    
    
    
         name = cursor.getString(nameIdx);
         Log.d("CONTENT",name);
         str[x]= name;
                 x++;
          } while(cursor.moveToNext());
    
         ArrayAdapter<String> arr = new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1,str);
    
         setListAdapter(arr);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      相关资源
      最近更新 更多