Xalion Xalion - 3 months ago 18
Android Question

Android: Getter of database in SQLite

I created database at stClass, and I want to use the same database in other class( ndClass). Android studio wanted to make all static so I did it, but i cannot resolve that

cannot be referenced from a static field


stClass:

public static Base db= new Base(this,null,null,0);// error in "this"
public static Base getDb() {
return db;
}


ndClass:

Base db = AddDate.getDb();


I know that problem is probably piss-easy...

Answer
public class Base extends SQLiteOpenHelper {

    private static Base sInstance;

    private static final String DATABASE_NAME = "database name";
    private static final String DATABASE_TABLE = "table";
    private static final int DATABASE_VERSION = 1;

    public static synchronized Base getInstance(Context applicationContext) {

        // Make sure it is application context, which will ensure that you
        // don't leak an Activity's context.
        if (sInstance == null) {
            sInstance = new Base(applicationContext);
        }
        return sInstance;
    }

    /**
     * private constructor prevent direct instantiation.
     */
    private Base(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

}
Comments