我正在處理數據庫,我試圖用我的表的每一行填充一個ListView。我已經成功創建並查詢了數據,但我無法使用SimpleCursorAdapter獲得任何顯示在ListView中的內容。SimpleCursorAdapter來填充ListView
public class History extends ListActivity {
SQLiteDatabase db;
DbHelper DbHelper;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
DbHelper = new DbHelper(this);
db = DbHelper.getWritableDatabase();
lv = getListView();
final String[] from = { DbHelper.TYPE, DbHelper.TITLE, DbHelper.CONTENT };
final String[] column = { DbHelper.C_ID, DbHelper.TYPE, DbHelper.TITLE,
DbHelper.CONTENT };
final int[] to = { R.id.list_row_title, R.id.list_row_content };
Cursor cursor = db.query(DbHelper.TABLE_NAME, column, null, null, null,
null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.history_list_row, cursor, from, to);
lv.setAdapter(adapter);
/*
* Display as Toast for development purposes
*/
// move to first row
cursor.moveToFirst();
// move to the next item each time
while (cursor.moveToNext()) {
// get string and column index from cursor
String name = cursor
.getString(cursor.getColumnIndex(DbHelper.TYPE));
String title = cursor.getString(cursor
.getColumnIndex(DbHelper.TITLE));
String content = cursor.getString(cursor
.getColumnIndex(DbHelper.CONTENT));
Toast.makeText(this,
"Title: " + title + "\n" + "Content: " + content,
Toast.LENGTH_SHORT).show();
}
cursor.close();
}
}
這是我的自定義的ListView行從數據庫
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/list_row_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/list_row_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/list_row_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type"
android:textAppearance="?android:attr/textAppearanceSmall" />
敬酒消息顯示完美顯示3個字符串,但沒有出現在ListView。
我不認爲你應該搞砸,更不要關閉適配器外的光標,因爲它會弄亂光標位置和加載數據。關閉的光標在你的適配器內不好。 – ebarrenechea 2013-02-22 00:45:50
如果你不'',你可以將'null'傳遞給['changeCursor(Cursor)'](http://developer.android.com/reference/android/widget/CursorAdapter.html#changeCursor(android.database.Cursor)不再需要它了。如果你使用['LoaderCallbacks'](http://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html),你可以在['onLoaderReset()'](http:// developer .android.com/reference/android/app/LoaderManager.LoaderCallbacks.html#onLoaderReset(android.content.Loader))。否則,請勿關閉適配器外部的光標。適配器管理光標本身。 –
2013-02-22 01:05:00