I am making inner static class as a singleton to avoid A SQLiteConnection object for database 'db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
I can close the mDb.close
after db transactions using mDb
instance(in case of just static class) ,
I want to know is it right way to make inner static class as a singleton in a constructor of outer class ??
private ImageDb mDb;
public class SavedImages extends BaseAdapter implements ListAdapter {
public SavedImages(Activity context) {
ImageDb.moveFromCacheDirectoryIfNecessary(context);
mDb = ImageDb.getInstance(context);
}
static class ImageDb extends SQLiteOpenHelper {
final static int DB_VERSION = 1;
final static String DB_NAME = "wallpaper_images.db";
final static String TABLE_NAME = "wallpaper_images";
final static String COLUMN_ID = "id";
final static String COLUMN_IMAGE_THUMBNAIL_FILENAME = "image_thumbnail";
final static String COLUMN_IMAGE_FILENAME = "image";
//Context mContext;
private static ImageDb mImageDb;
public static ImageDb getInstance(Context context) {
if (mImageDb == null) {
mImageDb = new ImageDb(context.getApplicationContext());
}
return mImageDb;
}
private ImageDb(Context context) {
super(context, context.getDatabasePath(DB_NAME).getPath(), null, DB_VERSION);
}
public static void moveFromCacheDirectoryIfNecessary(Context context) {
//static method
}
@Override
public void onCreate(SQLiteDatabase database) {
//oncreate db
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//onupgrade db
}
}
}
答案 0 :(得分:0)
实现此目的的正确方法是使文件具有名为A
的类public class A {
private static class SingletoneHolder {
//here you declare the instance of what you want
}
public static YourInstance getInstance(){
return YourInstance;
}
}
这样,只要您想在应用内部访问,就可以访问此类的实例。
答案 1 :(得分:-1)
class TestOuter2{
static int data=30;
static class Inner{
static void msg() {
System.out.println("data is "+data);
}
}
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}