无法正常使用Android ListView

时间:2015-01-12 14:38:56

标签: java android sqlite listview android-listview

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

  

java.lang.RuntimeException:您的内容必须有一个ListView,其id属性为'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;

    }

Listview xml代码:

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法是创建扩展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一起使用。在这种情况下,片段或活动在提供的ListView布局中搜索预定义的android:id属性设置为@android:id / list。