带有游标适配器的列表视图



我正在开发一个应用程序,它使用CursorAdapter显示电话联系人。当我运行它时,我遇到了一个列表视图,该视图仅重复一个联系人作为下面的联系人("David"是我的联系人之一,只是在Listview中重复)

大卫017224860

大卫017224860

大卫017224860

大卫017224860

大卫017224860

大卫017224860.

.

.

.

我的活动看起来像

public class Contacts extends Activity {    
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contacts);
    Cursor cursor = getContentResolver()
        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
               null, null, null, null);
    startManagingCursor(cursor);
    ContactCursorAdapterCT adapter= new ContactCursorAdapterCT(Contacts.this, cursor);
     ListView contactLV = (ListView) findViewById(R.id.listviewblcontactsDB);
    contactLV.setAdapter(adapter);

我的光标适配器看起来像:

public class ContactCursorAdapterCT extends CursorAdapter {
       public ContactCursorAdapterCT(Context context, Cursor c) {
    super(context, c);
    // TODO Auto-generated constructor stub
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
    while (cursor.moveToNext()) {
        TextView name = (TextView)view.findViewById(R.id.blacklistDB1);               
          name.setText(cursor.getString(cursor.getColumnIndex
          (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
        TextView phone = (TextView)view.findViewById(R.id.blacklistDB2); 
          phone.setText(cursor.getString(cursor.getColumnIndex
          (ContactsContract.CommonDataKinds.Phone.NUMBER)));
    }
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
    // TODO Auto-generated method stub
    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.lv, parent, false);
            bindView(v, context, cursor);
           return v;
}

我注意到了几点:

  1. 光标适配器为您移动光标,取出您的呼叫cursor.moveToNext()
  2. 适配器的getView()自行调用newView()bindView();您不应该自己调用这些方法。
  3. 您应该在Google IO上观看Android开发人员的讲座,以了解有关加速适配器的提示和技巧。提示如下:
    • 使用 ViewHolder,而不是反复调用findViewById()
    • 保存游标的索引,而不是重复调用getColumnIndex()
    • 获取一次布局膨胀并保留本地引用。

另外,我建议你从使用CursorManager切换到使用CursorLoader。这在 Android API 指南的加载器下有记录。您可能会发现有用的一个特定示例是这里。

游标

适配器将游标"连接"到列表视图。光标是数据的数据视图,列表视图是相同数据的 UI 视图。您无需编写任何程序即可使 ListView 与光标保持同步,这一切都是自动处理的。

您确实需要告诉 ListView 它应该在游标中显示哪些列,请参阅 SimpleCursorAdapter 类的文档。我通常使用该类,除非在将数据从光标移动到列表视图时必须修改数据。

最新更新