我已经对我的SQLite数据库上的IO做了一些测量。从此数据库加载一些对象大约需要6秒钟。我有一个扩展Asynctask的类,这个类的工作是加载我数据库中的最后10个条目。这个类是这样构造的:
import View.CustomAdapter;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.util.Log;
import android.view.*;
public class LoadCases extends AsyncTask<String, Integer, ArrayList<Case>> {
ProgressBar progressBar;
ArrayList<Case> lastTenCases;
CustomAdapter cAdapter;
Context context;
ListView lastCases;
DatabaseHandler db;
TextView loading;
int options;
public LoadCases(ProgressBar progressBar, Context context, ListView lastCases, TextView loading, ArrayList<Case> lastTenCases) {
this.progressBar = progressBar;
this.context = context;
this.lastCases = lastCases;
this.loading = loading;
this.lastTenCases = lastTenCases;
db = new DatabaseHandler(context);
}
public void onPreExecute() {
progressBar.incrementProgressBy(1);
}
@Override
protected ArrayList<Case> doInBackground(String... params) {
long start = System.nanoTime();
lastTenCases = db.getAllCases(10);
long end = System.nanoTime();
Log.d("TIME TO LOAD CASES FROM BASE: ", Long.toString((end-start)/1000000000));
return lastTenCases;
}
public void onPostExecute(ArrayList<Case> result) {
progressBar.setVisibility(View.GONE);
loading.setVisibility(View.GONE);
cAdapter = new CustomAdapter(context, lastTenCases);
cAdapter.notifyDataSetChanged();
lastCases.setAdapter(cAdapter);
} }
正如您所看到的,测量是在我调用方法getAllCases(10)
long start = System.nanoTime();
lastTenCases = db.getAllCases(10);
long end = System.nanoTime();
Log.d("TIME TO LOAD CASES FROM BASE: ", Long.toString((end-start)/1000000000));
如前所述,这将使我从数据库中加载10个案例大约需要6秒钟。
现在,转到getAllCases
方法
public ArrayList<Case> getAllCases(int take) {
ArrayList<Case> caseList = new ArrayList<Case>();
String selectQuery = "SELECT *, (strftime('%s', DATE) * 1000) AS DATENOW FROM " + TABLE_CASES + " ORDER BY " + DATE + " DESC LIMIT " + Integer.toString(take) + " ;";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Case c = new Case();
long millis = cursor.getLong(cursor.getColumnIndexOrThrow("DATENOW"));
Date addedOn = new Date(millis);
c.setCaseNumber(cursor.getString(0));
c.setDate(addedOn.toLocaleString());
c.setStatus(cursor.getString(cursor.getColumnIndex(STATUS)));
caseList.add(c);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return caseList;
}
此方法将构造Case
个对象,并将其添加到ArrayList
。将返回此ArrayList。是的,我想你了解代码。但是6秒,真的吗?我究竟做错了什么?我怎样才能加快这项操作?
谢谢!
答案 0 :(得分:1)
这取决于您的数据库结构(例如,如果TABLE_CASES只是另一个复杂查询)和TABLE_CASES
中的字段数,但至少可以改进以下几点:
strftime('%s', DATE) * 1000)
- 每当你需要获得CASE时,你真的需要计算它吗?存储该值而不是计算肯定会加快查询速度; new Date(millis)
可能应该移出循环; getColumnIndexOrThrow
和getColumnIndex
的调用也应该移出循环; toLocaleString
在API级别1中已弃用,请使用DateFormat 最后,我建议遵循this guide for traceview并确定延迟是否实际发生在SQLite中或刚好在它之后的循环中。