【问题标题】:Why does my async task handler for a sqlite database trigger postExecute immediately为什么我的 sqlite 数据库的异步任务处理程序会立即触发 postExecute
【发布时间】:2013-09-11 05:30:39
【问题描述】:

我有一个异步类,它打开一个 sqlite 数据库,如果是第一次运行,数据库将填充大约需要 10 秒才能完成的数据。即使后台仍在完成工作,异步任务也会立即完成。我认为这与 sqlite 的 oncreate 方法可能会执行另一个异步任务或其他事情有关

class BuildDatabase extends AsyncTask<Void, Void, Void> {

    ProgressDialog loading;

    @Override
    protected void onPreExecute() {
        loading = ProgressDialog.show(ctx, "Please wait...", "Building database, this may take a few seconds", true);
    }

    @Override
    protected Void doInBackground(Void... params) {
        // open up the database, if its the first time running the data will
        // be populated
        db = new SQLiteWrapper(ctx); //takes 1-10 seconds
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        Log.d(TAG,"post execute");
        loading.dismiss();
    }
}

sqlite helper 类的主要方法如下所示

public class SQLiteWrapper extends SQLiteOpenHelper {
public SQLiteWrapper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    ctx = context;

}

@SuppressWarnings("deprecation")
@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);

    // populate our database with data from the zones file
    try {
        database.setLockingEnabled(false);
        buildDatabase(database);
    }
    finally {
        database.setLockingEnabled(true);
    }

}
}

如果你熟悉这个类 onCreate 只被调用并且数据库不存在。 如果我在数据库构造函数中手动调用 onCreate(),则会显示进度对话框。 想法?

【问题讨论】:

    标签: android asynchronous android-asynctask android-sqlite android-progressbar


    【解决方案1】:

    onCreate 只会在您实际打开 数据库(并且它还不存在)时被调用。

    this.getWritebleDatabase() 添加到SQLiteWrapper 构造函数中,如下所示:

    public SQLiteWrapper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        ctx = context;
        this.getWritableDatabase();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 2022-12-28
      相关资源
      最近更新 更多