无法使 Android ListView 正常工作

Can't Get Android ListView Working Properly

我正在尝试为我的应用制作 ListView,但我得到以下答案

java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

当我成功地使 ListView 工作时出现此问题,但在添加或删除数据 mysq sqlite 数据库后它不会更新。

我的ListView代码;

MessageRepo repo = new MessageRepo(this);
msgsList =  repo.getMessageList();
lv = getListView();
ArrayAdapter<HashMap<String, String>> arrayAdapter = new ArrayAdapter<HashMap<String, String>>(this,android.R.layout.simple_list_item_1, msgsList);
setListAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();//my second problem

getMessageList() 代码:

public ArrayList<HashMap<String, String>>  getMessageList() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT  " +
                Message.KEY_ID + "," +
                Message.KEY_message +
                " FROM " + Message.TABLE;

        //Message Message = new Message();
        ArrayList<HashMap<String, String>> MessageList = new ArrayList<HashMap<String, String>>();


        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list

        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> Messagehash = new HashMap<String, String>();
                Messagehash.put("id", cursor.getString(cursor.getColumnIndex(Message.KEY_ID)));
                Messagehash.put("message", cursor.getString(cursor.getColumnIndex(Message.KEY_message)));
                MessageList.add(Messagehash);

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return MessageList;

    }

列表视图xml代码:

<ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

提前致谢!

最好的方法是创建一个扩展 ArrayAdapter 的适配器 像这样:

private class StableArrayAdapter extends ArrayAdapter<String> {

    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

    public StableArrayAdapter(Context context, int textViewResourceId,
        Cursor cameFromDB) {
      super(context, textViewResourceId, objects);
      for (int i = 0; i < objects.size(); ++i) {
        //Put your cursor logic here
      }
    }

    @Override
    public long getItemId(int position) {
      String item = getItem(position);
      return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
      return true;
    }

  }

} 

你的XML应该是这样的:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" /> 

您可以将自定义布局与 ListActivity 或 ListFragment 结合使用。在这种情况下,片段或 activity 在提供的布局中搜索预定义 android:id 属性设置为 @android:id/list. 的 ListView