我有一个数据库,我创建了一个具有私有静态类的Database类,DbHelper扩展了sqliteOpenHelper以帮助我管理我的数据库.
该数据库可以从四种不同的活动中访问.
我有这个公共的voID onCreate(sqliteDatabase db),它创建了我的数据库表并为这些表添加了值.由于程序仅在用户第一次运行应用程序时进入此处,因此我想创建一个ProgressDialog.
这就是我所拥有的:
OverrIDepublic voID onCreate(sqliteDatabase db) { ProgressDialog progresso = ProgressDialog.show(context, "Info", "Loading DB" ); // Code to create the tables and add the values progress.dismiss();}
有两个问题.
第一:
由于这可以从4个不同的活动中访问,我如何获得上下文?
制造:
Context context = getAplicationContext();
第二:
为什么我不能使用strings.xml中的字符串?
我做不到这个:
ProgressDialog progresso = ProgressDialog.show(context, getString(R.string.driProgressTitle), getString(R.string.driProgressMessage) );
UPDATE
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); } }}
使用上面的代码我收到此错误没有封闭类型数据库的实例可访问.必须使用类型为Database的封闭实例限定分配(例如x.new A(),其中x是Database的实例).在new loadDB().execute();.
解决方法:
你不能从构造函数访问Context吗?
sqliteOpenHelper(Context context, String name, sqliteDatabase.CursorFactory factory, int version)sqliteOpenHelper(Context context, String name, sqliteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler)
编辑:
你的代码:
public DbHelper(Context context) { super(context, BD_name, null, BD_VERSION); // Todo auto-generated method stub }
此时您可以访问上下文..您可以执行类似添加称为上下文的字段之类的 *** 作,然后执行以下 *** 作:
Context context;public DbHelper(Context context) { super(context, BD_name, null, BD_VERSION); // Todo auto-generated method stub this.context = context; }
现在,您可以访问班级中的任何位置的上下文?假设在onCreate之前调用构造函数.
总结以上是内存溢出为你收集整理的Android获取数据库中的上下文全部内容,希望文章能够帮你解决Android获取数据库中的上下文所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)