當我的database
創建時,如何顯示ProgressDialog
。這隻顯示一次。使用AsyncTask創建數據庫時的Android ProgressDialog
我有這樣的代碼在我的活動:
baseDados.open();
ListView listContent = (ListView)findViewById(android.R.id.list);
Cursor query = baseDados.getData(1,0,null);
MyAdapt cursorAdapter = new MyAdapt(this, query,0);
listContent.setAdapter(cursorAdapter);
在第一次運行時,創建數據庫,填充和查詢的結果顯示在一個listview
。使用上面的代碼可以再次使用,但是這次數據庫不會被創建,因爲它已經被創建。
在互聯網上,我看到最好的方法是使用AsyncTaks
,但如果我使用AsyncTaks
,則在創建數據庫時顯示progressdialog和錯誤信息時遇到問題。
我創建了一個類來處理我的數據庫,並創建了我的AsyncTaks
。
這裏是我做了什麼:
public class Database {
private DbHelper DBHelper;
private final Context Context;
private SQLiteDatabase BaseDados;
static Context ctx;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, BD_NAME, null, BD_VERSION);
ctx = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
new loadDB().execute(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVesion) {
// Drop table if table exists
(....)
// creates new tables and data
onCreate(db);
}
public class loadDB extends AsyncTask<SQLiteDatabase, Void, Integer> {
ProgressDialog progresso;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progresso = ProgressDialog.show(ctx, "INFO", "Instaling for the first time"));
}
@Override
protected Integer doInBackground(SQLiteDatabase... params) {
SQLiteDatabase db = params[0];
// Code to create the tables and populate them
// Lots of code like below
db.execSQL("SQL statement goes here");
return 1;
}
@Override
protected void onPostExecute(Integer result) {
// Dismiss the ProgressDialog
progresso.dismiss();
super.onPostExecute(result);
}
}
}
public Database(Context c) {
Context = c;
}
public Database open() throws SQLException {
DBHelper = new DbHelper(Context);
BaseDados = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public Cursor getData(int tipo, long groupId, String query[]) {
// querys performed on the database
}
}
我有兩個問題。
問題1
ProgressDialog從未盡管它顯示需要差不多五秒鐘以創建和填充我的數據庫
問題2
在某一點上,應用程序崩潰和數據庫沒有正確創建,因爲查詢給出錯誤no such table
創建填充數據庫的代碼是OK,因爲如果在方法
@Override
public void onCreate(SQLiteDatabase db) {
new loadDB().execute(db);
}
我刪除new loadDB().execute(db);
,並把這個:
@Override
public void onCreate(SQLiteDatabase db) {
// SQL code that was on `doInBackground(SQLiteDatabase... params)`
}
你能告訴我什麼我做錯了嗎?
基本上Database.open是一旦DB存在必須只返回一個同步操作。 – njzk2
感謝您的解釋 – Favolas