【发布时间】:2012-08-24 16:45:23
【问题描述】:
我有一个数据库,我创建了一个 Database 类,其中包含一个 private static class DbHelper extends SQLiteOpenHelper 来帮助我管理我的数据库。
这个数据库是从四个不同的活动中访问的。
我有这个public void onCreate(SQLiteDatabase db),它是创建我的数据库表并向这些表添加值的原因。由于程序只在用户第一次运行应用时进入这里,所以我想创建一个ProgressDialog。
这就是我所拥有的:
Override
public void onCreate(SQLiteDatabase db) {
ProgressDialog progresso = ProgressDialog.show(context, "Info", "Loading DB" );
// Code to create the tables and add the values
progress.dismiss();
}
有 2 个问题。
第一:
既然可以从 4 个不同的活动中访问它,我如何获取上下文? 制作:
Context context = getAplicationContext();
第二:
为什么我不能使用 strings.xml 中的字符串? 我做不到:
ProgressDialog progresso = ProgressDialog.show(context, getString(R.string.driProgressTitle), getString(R.string.driProgressMessage) );
更新
public class Database {
ProgressDialog progresso;
private DbHelper DBHelper;
private final Context Context;
private SQLiteDatabase BaseDados;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, BD_NAME, null, BD_VERSION);
// TODO Auto-generated method stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// Whanted to show here the progress dialog
new loadDB().execute();
// Creates the table and adds the values
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVesion) {
db.execSQL("DROP TABLE IF EXISTS MYTABLE");
onCreate(db);
}
}
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[]) {
// Performs the querys to my database
}
return null;
}
public class loadDB extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... params) {
progresso = ProgressDialog.show(Context, Context.getString(R.string.ProgressTitle), Context.getString(R.string.ProgressMessage) );
return 1;
}
@Override
protected void onPostExecute(Integer result) {
progresso.dismiss();
super.onPostExecute(result);
}
}
}
使用上面的代码,我在new loadDB().execute(); 中收到此错误No enclosing instance of type Database is accessible. Must qualify the allocation with an enclosing instance of type Database (e.g. x.new A() where x is an instance of Database).。
【问题讨论】:
-
不,您不能在
doInBackground()方法中触摸与GUI 相关的任何内容。覆盖onPreExecute()并调用ProgressDialog.show()。 -
@wingman 好的。做到了。但是我应该打电话给
new loadDB().execute();吗? -
loadDB之外的任何地方,基本上在您活动的onStart()中。 -
@wingman 做新的 loadDB().execute();在我的
Database class it gives this error:的onCreate(SQLiteDatabase db)中没有可以访问数据库类型的封闭实例。必须使用数据库类型的封闭实例来限定分配(例如,x.new A(),其中 x 是数据库的实例)。` 在我的主类/活动的onCreate(Bundle savedInstanceState)中执行new loadDB().execute();会给出错误:loadDB cannot be resolved to a type.感谢您的帮助
标签: android database android-context