ProgressDialog
mydatabase
が作成されたときに何を表示するか。これは一度だけ表示されます。
私のアクティビティには次のコードがあります。
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
。
データベースを処理するクラスを作成し、そこにを作成しました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
}
}
私には2つの問題があります。
問題1
ProgressDialogは表示されませんが、データベースの作成と入力には約5秒かかります。
問題2
ある時点で、アプリがクラッシュし、クエリでエラーが発生するため、データベースが正しく作成されません。データベースにデータをno such table
入力するためのコードは、メソッド内の場合は問題ないためです。
@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)`
}
私が間違っていることを教えてもらえますか?