androidandroid-sqliteandroid-contextmain-activity

Access to SQLiteOpenHelper created in MainActivity


I have created a SQLiteOpenHelper object in MainActivity:

    public class ExchangeActivity extends AppCompatActivity {


public CurrencyDBHelper db;
private Handler handler;
private int delay = 30000;
private DataHandler dataHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    //create CurrencyDBHelper object
    db = new CurrencyDBHelper(this);
    Log.v("DBTag", "DB created");


    //Activity and UI
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_exchange);
    }}

My CurrencyDBHelper class code:

public class CurrencyDBHelper extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "LastCurrency.db";

//constructor
public CurrencyDBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE CURRENCY ("
            + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + "NAME TEXT, "
            + "RATE REAL); ");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

I need to call the db from the other class. How can I do this from the other class?

I tryed to create SQLiteOpenHelper not in MainActivity, but it does not work for me. It seems like I have to use Context, but I dont undestand hot do this.

Please help. Thanks!


Solution

  • 1) Move the DBHelper class to be a class in it's own right i.e CurrencyDBHelper.java should be :-

    public class CurrencyDBHelper extends SQLiteOpenHelper {
    
        public static final int DATABASE_VERSION = 1;
        public static final String DATABASE_NAME = "LastCurrency.db";
    
        //constructor
        public CurrencyDBHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE CURRENCY ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + "NAME TEXT, "
                    + "RATE REAL); ");
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    }
    

    2) In the activity in which you want to use the database use:-

    db = new CurrencyDBHelper(this);
    

    Note! this will NOT create the database. The database will only be created when an attempt is made to open it e.g. the getWRiteableDatabase or the getReadableDatabase is called.

    so 3)

    SQLiteDatabase mydb = db.getWritableDatabase();
    

    will result in the database being created (i.e the DBHelper's onCreate method will be called).

    Note! onCreate will only be called once for the lifetime of the database file. As such if you want to amend the structure of the database, when developing it's probably easiest to clear the Apps Data or uninstall and then re-install the App.

    At this stage there will be no data in the table.

    You could however query the empty table e.g :-

            Cursor csr = mydb.query("CURRENCY",null,null,null,null,null,null,null);
            Log.v("MYDB","Table CURRENCY has " +
                    Integer.toString(csr.getCount()) +
                    " rows"
            );
            for (int i=0; i < csr.getColumnCount(); i++) {
                Log.v("MYDB","Table CURRENCY has a column named " +
                        csr.getColumnName(i)
                );
            }
            csr.close();
    

    The using activity could then be :-

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            db = new CurrencyDBHelper(this);
            SQLiteDatabase mydb = db.getWritableDatabase();
            Cursor csr = mydb.query("CURRENCY",null,null,null,null,null,null,null);
            Log.v("MYDB","Table CURRENCY has " +
                    Integer.toString(csr.getCount()) +
                    " rows"
            );
            for (int i=0; i < csr.getColumnCount(); i++) {
                Log.v("MYDB","Table CURRENCY has a column named " +
                        csr.getColumnName(i)
                );
            }
            csr.close();
        }
    

    The output to the log would be along the lines of :-

    07-21 17:38:07.290 1886-1886/mjt.cardoniser V/MYDB: Table CURRENCY has 0 rows
    07-21 17:38:07.290 1886-1886/mjt.cardoniser V/MYDB: Table CURRENCY has a column named _id
    07-21 17:38:07.290 1886-1886/mjt.cardoniser V/MYDB: Table CURRENCY has a column named NAME
    07-21 17:38:07.290 1886-1886/mjt.cardoniser V/MYDB: Table CURRENCY has a column named RATE