[英]Displaying contents of database in listview in android
我的數據庫中有數據,我打算使用列表視圖顯示給用戶。這是我編寫的用於顯示內容的函數
public class List_View extends ListActivity {
ListView lv;
Databasehelp db = new Databasehelp(this);
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.displayitems);
List<String> items = new ArrayList<String>();
lv = (ListView)findViewById(android.R.id.list);
Cursor cursor = db.getAllTable1(); cursor.moveToFirst();
//startManagingCursor(cursor);
lv.setAdapter(new ArrayAdapter<String>(this,
R.layout.displayitems, items));
lv.setTextFilterEnabled(true);
ListAdapter adapter=new SimpleCursorAdapter(this,
R.layout.list_example_entry, cursor,
new String[] {"name"},
new int[] {R.id.name_entry});
setListAdapter(adapter);
}
}
布局是displayitems.xml,其中包含ID為“ list”的列表視圖,list_example_entry.xml包含ID為name_entry的線性布局內的textview
displayitems.xml
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
list_example_entry
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/name_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dip" />
</LinearLayout>
你們中的任何一個可以幫助我解決這個問題嗎?
您調用一個游標,然后嘗試設置一個數組適配器。 然后是游標適配器...
擺脫ArrayAdapter調用,這是沒有必要的。 當您將游標饋入適配器時,也不需要調用moveToFirst()
,適配器將負責此工作。
它看起來應該像這樣:
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.displayitems);
Cursor cursor = db.getAllTable1();
startManagingCursor(cursor);
SimpleCusrorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list_example_entry, cursor,
new String[] {"name"},
new int[] {R.id.name_entry});
setListAdapter(adapter);
}
編輯
該錯誤表示它的意思。 當您使用ListActivity時,它期望您的列表的ID為@id/android:list
。 因此,將您的ListView xml更改為如下所示:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
如果您評論中的最后一個問題與為什么不必執行findViewById
,那是因為您使用的是ListActivity,它會進行某些假設。 主要的原因是您的布局中有一個ListView,並且它具有上面提到的特定ID(這就是您收到該錯誤的原因)。 由於只有一個,並且它知道id是什么,因此無需專門對其進行調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.