我在Android工作室工作,我遇到了一个问题,我无法在我的DataHandler类中初始化我的sqlite实例,但我可以在我的MainActivity类中初始化它。
实施例: MainActivity类:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//valid
private SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("Database", Context.MODE_PRIVATE , null); //...
在datahandler类中:
public class DataHandler {
public static String[] names,dates;
//invalid: cannot resolve method
SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("HMDB", Context.MODE_PRIVATE , null);
所以,我这样做了
主要活动:
public SQLiteDatabase getSqLiteDatabase() {
return sqLiteDatabase;
}
数据处理程序中的:
MainActivity mainActivity;
SQLiteDatabase sqLiteDatabase = mainActivity.getSqLiteDatabase();
这是正确的方法吗?有没有更好的方法? sry如果难以理解
答案 0 :(得分:0)
最好的方法是使用此处所述的Singleton Pattern https://github.com/codepath/android_guides/wiki/Local-Databases-with-SQLiteOpenHelper
public class PostsDatabaseHelper extends SQLiteOpenHelper {
private static PostsDatabaseHelper sInstance;
// ...
public static synchronized PostsDatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (sInstance == null) {
sInstance = new PostsDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
/**
* Constructor should be private to prevent direct instantiation.
* Make a call to the static method "getInstance()" instead.
*/
private PostsDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
在你的MainActivity
中使用它
// In any activity just pass the context and use the singleton method
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
// or
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(context);
// or
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(getActivity());
// Do something with data via Cursor and
helper.close();
这种方法非常适合从服务,片段等应用程序的不同位置访问数据库......