我有一个相当大的数据库需要查询,以获取一些数据并在Android上的ListView中呈现。数据库大小约为5MB,存储在SD卡上。它有2个表中的60k条记录。问题在于查询该数据库以获取某个特定列的所有记录需要非常长的时间 - 在模拟器和我的手机上都需要几分钟的时间。我已经尝试了所有方法 - 将这些数据存储在平面文件、XML中 - sqlite是我的最后希望。这是我用于打开数据库并查询它的类:
public class DataHelper {
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "TableName";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
// this.db = openHelper.getReadableDatabase();
this.db = SQLiteDatabase.openDatabase(
Environment.getExternalStorageDirectory()
+ "/myDB.db", null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS);
// this.insertStmt = this.db.compileStatement(INSERT);
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public List<String> selectBrands() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "ColumnName" },
null, null, null, null, null);
}
if (cursor.moveToFirst()) {
do {
if (!(list.contains(cursor.getString(0)))) {
list.add(cursor.getString(0));
}
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, null, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}
并且在ListView部分进行操作:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
ctxContext = this.getApplicationContext();
lView = (ListView) findViewById(R.id.ListView01);
lView.setTextFilterEnabled(true);
ParseSQLITETask task = new ParseSQLITETask();
task.execute(null);
} catch (Exception e) {
LogErr(e.getMessage());
}
}
private class ParseSQLITETask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... urls) {
try {
DataHelper dHelper = new DataHelper(getApplicationContext());
list = (ArrayList<String>) dHelper.selectBrands();
} catch (Exception e) {
LogErr(e.getMessage());
}
return null;
}
@Override
protected void onProgressUpdate(Void... progress) {
}
@Override
protected void onPostExecute(Void result) {
try {
lView.setAdapter(new ArrayAdapter<String>(ctxContext,
R.layout.list_item, list));
} catch (Exception e) {
LogErr(e.getMessage());
}
}
}