运行查询游标后,保存这样的数据
1 - R. Robert
1 - F. Ahmed
2 - M. Rahman
2 - T. Banik
3 - L. Morison
我希望通过特定ID获取数据,如1和wnat,将其存储在数组中。我试过这个
String [] Names = null;
cursor.moveToFirst();
do{
if(cursor.getString(cursor.getColumnIndexOrThrow("_id")).equalsIgnoreCase("1")){
String namesAuth = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
Names[cursor.getInt(cursor.getColumnIndexOrThrow("_id"))] = namesAuth;
}
}while(cursor.moveToNext());
我想要一个像这样的格式[R.Robert,F.Ahmed]。这可能吗 ?谢谢
答案 0 :(得分:0)
不是尝试过滤游标中的数据,而是使用所需的过滤器构建查询:
SQLiteDatabase db = getReadableDatabase();
String[] columns = new String[]{ /* Columns to include in the query */ };
Cursor cursor = db.query(TABLE_NAME, columns,"_id=?", new String[]{"1"}, null, null, null);
然后只需遍历光标
ArrayList<String> names = new ArrayList<String>();
int columnIndex = cursor.getColumnIndexOrThrow("NAME");
if (cursor.moveToFirst()) {
do {
names.add(cursor.getString(columnIndex);
}while (cursor.moveToNext());
}
答案 1 :(得分:0)
这不起作用,因为你必须用一个长度初始化数组,并且该代码应该(?)产生NullPointerException
。
您可以使用ArrayList
并将字符串添加到其中,就像这样。
ArrayList<String> names = new ArrayList<String>();
cursor.moveToFirst();
do{
if(cursor.getString(cursor.getColumnIndexOrThrow("_id")).equalsIgnoreCase("1")){
String namesAuth = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
names.add(namesAuth);
}
}while(cursor.moveToNext());