我的代码是:
DatabaseHandler db = new DatabaseHandler(this);
System.out.println("Start - " + System.currentTimeMillis());
for (int i = 1; i < db.getChampsCount() + 1; i++) {
String name = db.getChampInfo(i, "name");
String title = db.getChampInfo(i, "title");
String thumb = db.getChampInfo(i, "thumb");
System.out.println("End - " + System.currentTimeMillis());
[...]
}
和这个
String getChampInfo(int id, String col) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + col + " FROM champions WHERE id = " + id, new String[] {});
if (cursor != null)
cursor.moveToFirst();
db.close();
return cursor.getString(0);
}
这是DatabaseHelper类的一部分
这个运行没有问题,但是问题是它执行起来时间很长(在我的android机子上是2089ms)。这些字符串是UI的一部分,所以我不认为我能把他放到另外一个线程中。如果要让这段代码跑的快一点,我应该怎么做?
确切的说是110行
不应该是用单独的语句,你不应该用单独的sql语句?
只是创建一个ArrayList,在这个activity类中存储所有需要的数值。
例如: ArrayList myData;
现在在数据库类的帮助下写一个function,就像下边:
//得到你想要的数据
public ArrayList<String> getAllData() {
ArrayList<String> subTitleList = null;
Cursor cursor = null;
try {
String queryString = "SELECT * FROM champions";
cursor = db.rawQuery(queryString, null);
if (cursor != null && cursor.moveToFirst()) {
subTitleList = new ArrayList<String>();
do {
String nextUser = new String(cursor.getString(cursor.getColumnIndex("name")));
String nextUser = new String(cursor.getString(cursor.getColumnIndex("title")));
String nextUser = new String(cursor.getString(cursor.getColumnIndex("thumb")));
subTitleList.add(nextUser);
}
while (cursor.moveToNext());
System.out.println("it comes in SubTitleList");
}
}
catch (Exception e) {
e.printStackTrace();
subTitleList = null;
}
finally {
if (cursor != null && !cursor.isClosed()) {
cursor.deactivate();
cursor.close();
cursor = null;
}
if(db != null){
db.close();
}
}
//System.out.println("SubTitleList is: "+subTitleList);
return subTitleList;
}
现在在你的activity类中你可以调用这个方法,然后从myData ArrayList获得所有你需要的数据。
myData = db.getAllData(); // 我想如果你想要抓所有的数据的话是不需要ID的。
希望你能明白
getChampInfo本身运行就有错,哪有先close db再取cursor的。
而且如果这样返回所有值的方法,都是使用cursor打开一次,然后返回一个对象列表或者什么的。
难道从来没写过数据库?