在自定义列表视图中显示联系人姓名和电话号码

5
有人能告诉我如何在自定义列表视图中显示电话号码和联系人姓名吗?以下是代码。
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class AddContacts extends Activity implements OnClickListener {

    ListView list;
    Cursor cursor;
    SimpleCursorAdapter adapter;
    String phoneNumber;
    Button AddNumber;
    EditText number1;
    EditText number2;
    EditText number3;
    String contact1;
    String contact2;
    CheckBox checkBox;
    String contact_name;

    static final String TAG = "In AddContacts";

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        AddNumber = (Button) findViewById(R.id.AddNumbers);
        number1 = (EditText) findViewById(R.id.NumberField1);
        number2 = (EditText) findViewById(R.id.NumberField2);
        number3 = (EditText) findViewById(R.id.NumberField3);
        AddNumber.setOnClickListener(this);
        list = (ListView) findViewById(R.id.lists);


        Log.d(TAG, "onCreate");



        Cursor cursor = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, null);

        String[] nameNumberArray = new String[cursor.getCount()];
        Log.d("rows", Integer.toString(cursor.getCount()));

        Log.d("phone", "here");
        while (cursor.moveToNext()) {
            String phoneNumber =

            cursor.getString(cursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            Log.i("Number + Name", phoneNumber + name);
        }
        if (cursor.getCount() > 0) {

            int i = 0;
            if (cursor.moveToFirst()) {
                do {
                    phoneNumber = cursor
                            .getString(cursor
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                    contact_name = cursor
                            .getString(cursor
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    nameNumberArray[i] = contact_name + "  , " + phoneNumber;
                    i++;
                } while (cursor.moveToNext());
            }

        }

        final String[] FROM = { nameNumberArray[0], nameNumberArray[1] };
        final int[] TO = { R.id.contact_name, R.id.phone_number, };
        adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, FROM, TO);
        list.setAdapter(adapter);
        cursor.close();
    }

    @Override
    public void onClick(View v) {


        Log.d(TAG, "onClicked method");


    }
}

ROW.xml文件是一个带有复选框和两个textView的自定义listView。该代码从联系人中提取数据并在LogCat中显示。我无法使用simpleCursorAdapter在我的自定义视图中显示名称和号码,无法解决此问题。

row.xml文件

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/contact_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="John Doe"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/phone_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/contact_name"
        android:text="(999)999-9999"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <CheckBox
        android:id="@+id/checkBox_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

有人可以指引我吗? 谢谢。


你想使用自定义适配器吗?我有一个解决方案,可以使用自定义适配器显示姓名和电话号码。 - Raghunandan
我可以试一下。我需要为此摆脱simpleCursorAdapter吗? - user2511882
如果你想的话,我可以提供另一种解决方案。 - Raghunandan
你有什么可以帮我处理SimpleCursor的吗?如果没有,我可以尝试使用自定义适配器。 - user2511882
不,我不使用SimpleCursorAdapter。但是我使用自定义适配器。 - Raghunandan
显示剩余2条评论
2个回答

15

由于提问者要求使用自定义适配器的解决方案,我在评论区发布了以下内容。

Display.java

public class Display extends Activity implements OnItemClickListener{

    List<String> name1 = new ArrayList<String>();
    List<String> phno1 = new ArrayList<String>();
    MyAdapter ma ;
    Button select;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display);

        getAllContacts(this.getContentResolver());
        ListView lv= (ListView) findViewById(R.id.lv);
            ma = new MyAdapter();
            lv.setAdapter(ma);
            lv.setOnItemClickListener(this); 
            lv.setItemsCanFocus(false);
            lv.setTextFilterEnabled(true);
            // adding
           select = (Button) findViewById(R.id.button1);
        select.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                  StringBuilder checkedcontacts= new StringBuilder();
                System.out.println(".............."+ma.mCheckStates.size());
                for(int i = 0; i < name1.size(); i++)

                    {
                    if(ma.mCheckStates.get(i)==true)
                    {
                         checkedcontacts.append(name1.get(i).toString());
                         checkedcontacts.append("\n");

                    }
                    else
                    {
                        System.out.println("Not Checked......"+name1.get(i).toString());
                    }


                }

                Toast.makeText(Display.this, checkedcontacts,1000).show();
            }       
        });


    }
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
         ma.toggle(arg2);
    }

    public  void getAllContacts(ContentResolver cr) {

        Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
          String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
          String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
          System.out.println(".................."+phoneNumber); 
          name1.add(name);
          phno1.add(phoneNumber);
        }

        phones.close();
     }
    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
    {  private SparseBooleanArray mCheckStates;
       LayoutInflater mInflater;
        TextView tv1,tv;
        CheckBox cb;
        MyAdapter()
        {
            mCheckStates = new SparseBooleanArray(name1.size());
            mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name1.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub

            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi=convertView;
            if(convertView==null)
             vi = mInflater.inflate(R.layout.row, null); 
             TextView tv= (TextView) vi.findViewById(R.id.textView1);
             tv1= (TextView) vi.findViewById(R.id.textView2);
             cb = (CheckBox) vi.findViewById(R.id.checkBox1);
             tv.setText("Name :"+ name1.get(position));
             tv1.setText("Phone No :"+ phno1.get(position));
             cb.setTag(position);
             cb.setChecked(mCheckStates.get(position, false));
             cb.setOnCheckedChangeListener(this);

            return vi;
        }
         public boolean isChecked(int position) {
                return mCheckStates.get(position, false);
            }

            public void setChecked(int position, boolean isChecked) {
                mCheckStates.put(position, isChecked);
                System.out.println("hello...........");
                notifyDataSetChanged();
            }

            public void toggle(int position) {
                setChecked(position, !isChecked(position));
            }
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            // TODO Auto-generated method stub

             mCheckStates.put((Integer) buttonView.getTag(), isChecked);         
        }   
    }   
}

显示.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   <ListView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@+id/button1"

       android:id="@+id/lv"/>

     <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:text="Select" />

</RelativeLayout>

解释:

以上使用了自定义适配器。一个带有2个文本视图和一个复选框的自定义布局row.xml被为每一行填充。getAllContacts()将从通讯录中获取所有联系人并存储在列表中。

自定义适配器将在为每一行填充的自定义布局中显示项目。

当您选择复选框并单击显示时,会弹出一个Toast,其中包含所选联系人的名称。

快照

enter image description here


2
这个东西就像魔法一样好用。我批准了它。我也很想点赞,但是我没有足够的声望。但是非常感谢!我已经花了近3个小时在这上面了...干杯! - user2511882
这段代码显示了我的一些重复值联系人 :( - kgandroid
@kgandroid 不,它不会。其次,你应该使用CursorAdapter。这种方法不高效。 - Raghunandan
我的日志中打印了名称和数字,但它们并没有按排序顺序排列。但是当我将它们绑定在列表中时,一切都出错了。它只显示3-4个重复的联系人。 - kgandroid
完美运行。要对电话簿条目进行排序,只需将光标更改为:Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, Phone.DISPLAY_NAME + " ASC"); - kgandroid
显示剩余13条评论

0

我认为在将 cursor 传递给 SimpleCursorAdapter 之前,你应该再次调用 cursor.moveToFirst(),因为现在你正在发送一个“完成”的游标。

除此之外,你的代码看起来很好。你可以将其与 这里 的代码进行比较,它做了类似的事情(但使用了用户定义的数据库)。


请问您能指出我应该更改哪一行吗? - user2511882

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接