如何更改此逻辑以处理170多个行。
// Getting All test
public List<Test> getAllTests(String str) {
List<Test> testList = new ArrayList<Test>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TESTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
//select rows by input string
if(cursor.getString(1).equals(str)){
Test test = new Test();
test.setId(Integer.parseInt(cursor.getString(0)));
test.setTest(cursor.getString(1));
test .setResult(Integer.parseInt(cursor.getString(2)));
// Adding test to list
testList.add(test);
}
} while (cursor.moveToNext());
}
//close database
db.close();
//return list data
return testList;
}
我想通过输入字符串选择所有行。它逻辑上可以在150行中正常运行,但是在160行之后缓慢运行并在170行时崩溃
最佳答案
// Getting All test
public List<Test> getAllTests(String str) {
List<Test> testList = new ArrayList<Test>();
// Select All Query
//String selectQuery = "SELECT * FROM " + TABLE_TESTS;
String selectQuery = "SELECT id,result FROM " + TABLE_TESTS + " where name ='" + str + "'";
// Now you are saving memory of one column.
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
Test test = new Test();
// moved outside loop to prevent creating new object every time.
do {
//select rows by input string
//if(cursor.getString(1).equals(str)){
// No need for if Codition any more
test.setId(Integer.parseInt(cursor.getString(0)));
//test.setTest(cursor.getString(1));
test.setTest(str);
test .setResult(Integer.parseInt(cursor.getString(2)));
// Adding test to list
testList.add(test);
//}
} while (cursor.moveToNext());
}
//close database
db.close();
//return list data
return testList;
}
关于Android SQLite在170行后崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31872792/