早些时候我问了这个问题question(在谷歌搜索后我读了一下使用你自己的SQLite database for Android app。
所以,我有一个简单的数据库,其中包含2列(_id和引号)。我需要做的是从数据库中获取所有引号并在TextView中逐个显示它们。
我在DataBaseHelper.java中有这个:
private SQLiteDatabase myDataBase;
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor mCursor = myDataBase.query(true, DB_NAME, null, new String[] + "=" + "_id", null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
我该怎么办?感谢
答案 0 :(得分:3)
这个函数是我从“db”是数据库实例的数据库中获取数据的方法。 此函数将返回一个2D字符串数组,其中[0] [x]是它获取的第一行,[1] [x]是第二行,等等;并且x是列,在您的情况下[0] [1]将是数据库中的第一个引号。
public String[][] customQuery(String query) {
Cursor cur = null;
try {
cur = db.rawQuery(query,null);
} catch(SQLException e) {
Log.d("DATABASE", e.toString());
}
String data[][] = new String[cur.getCount()][cur.getColumnCount()];
if (cur != null) {
int i = 0;
while (cur.moveToNext()) {
int j = 0;
while (j < cur.getColumnCount()) {
data[i][j] = cur.getString(j);
j++;
}
i++;
cur.moveToNext();
}
cur.close();
}
return data;
}
答案 1 :(得分:2)
Johan的解决方案没问题,但你应该考虑使用逻辑对象。大多数情况下,表的一行代表一个逻辑对象。您应该将数据库行提取到一个对象中,以便您可以轻松地使用它们。
Bookmark
对象的示例:
public static List<Bookmark> getBookmarks(SQLiteDatabase db, long emagId) {
List<Bookmark> bookmarksList = null;
Cursor cursor = null;
try {
// WHERE clause for the SELECT query
final String where = Bookmark.EMAG_ID + " = " + emagId;
cursor = db.query(Bookmark.TABLE, new String[] {}, where, null, null, null, null);
bookmarksList = new ArrayList<Bookmark>();
while (cursor.moveToNext()) {
Bookmark bookmark = new Bookmark();
bookmark.id = cursor.getLong(cursor.getColumnIndex(Bookmark.ID));
bookmark.emag_id = cursor.getLong(cursor.getColumnIndex(Bookmark.EMAG_ID));
bookmark.page_number = cursor.getInt(cursor.getColumnIndex(Bookmark.PAGE_NUMBER));
bookmark.article_id = cursor.getLong(cursor.getColumnIndex(Bookmark.ARTICLE_ID));
bookmark.ref_html = cursor.getString(cursor.getColumnIndex(Bookmark.REF_HTML));
bookmark.ref_text = cursor.getString(cursor.getColumnIndex(Bookmark.REF_TEXT));
bookmark.ref_html = bookmark.ref_html;
bookmark.ref_text = "Page: " + bookmark.page_number;
bookmark.resource_id = cursor.getLong(cursor.getColumnIndex(Bookmark.RESOURCE_ID));
bookmark.resource_type = cursor.getInt(cursor.getColumnIndex(Bookmark.RESOURCE_TYPE));
bookmark.source_type = cursor.getInt(cursor.getColumnIndex(Bookmark.SOURCE_TYPE));
bookmark.content_path = cursor.getString(cursor.getColumnIndex(Bookmark.CONTENT_PATH));
bookmarksList.add(bookmark);
}
} catch (Exception e) {
Log.e(LOG_TAG, "::getBookmarksForEmagId", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return bookmarksList;
}
我在您的问题new String[] + "=" + "_id"
中看到了这段代码。我认为这不会起作用......
答案 2 :(得分:1)