下面是我用来获取存储在SQLite表中的所有结果的代码.我遇到的问题是,当我知道数据库中有21行时,它仅返回一行.
public HashMap fetchResults(String TABLE_NAME, String sql) {
HashMap table = new HashMap();
if(sql == null)
sql = "";
String selectQuery = "SELECT * FROM " + TABLE_NAME + " " + sql;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] columns = null;
switch(TABLE_NAME ){
case "projects":
columns = dbTables.projectsColumns;
break;
}
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int n=1;
for(int i=0; i
table.put(columns[i], cursor.getString(n));
n++;
}
}
//move to the next row
cursor.moveToNext();
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching " + TABLE_NAME + " from Sqlite: " + table.toString());
return table;
}
db调用在一个片段中进行,如下所示.
HashMap projects = db.fetchResults(dbTables.TABLE_PROJECTS, null);
for (String key : projects.keySet()) {
if(key == "projectname"){
System.out.println("Key: " + key + ", Value: " + projects.get(key));
menuList.add(projects.get(key));
}
}
解决方法:
您只在那里检索一行:
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int n=1;
for(int i=0; i
table.put(columns[i], cursor.getString(n));
n++;
}
}
您必须迭代游标才能获得所有结果:
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
while(cursor.moveToNext()) {
for (int i = 0; i < columns.length; i++) {
table.put(columns[i], cursor.getString(i));
}
}
}
但是您的表将列出每一行的所有列值.如果要使用带有行条目的表,请定义一个用于存储列值的类.
标签:sqlite,cursor,java,android,database
来源: https://codeday.me/bug/20191028/1950823.html