My aim is to have a class containing all functions which perform database operations cleanly and neatly - which can also be called with a single line of code, eg; DbFunctions.AddContact("fName", "lName");
I have a DBAdapter class which I have read in a tutorial:
public class DBAdapter {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "contacts";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE =
"create table contacts (_id integer primary key autoincrement, "
+ "name text not null, email text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
// some other database functions here... inserts, updates etc
}
And I have created my own class to handle all calls to the DBAdapter:
public static class DatabasesActivity extends Activity
{
static DBAdapter db;
// Called when activity is first created
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static long addContact(String name, String email)
{
if (db == null) {
db = new DBAdapter(this); // <--- compiler error here
}
db.open();
long id = db.insertContact("Joe Bloggs", "joe@bloggs.com");
db.close();
return id;
}
}
In the addContact
method, on the line: db = new DBAdapter(this);
, I get the following error: Cannot use 'this' in a static context
.
I am familiar with OOP concepts so I understand why I am getting this error - but being new to java itself, I am looking for alternate methods on what I'm trying to achieve. The DBAdapter class constructor takes in a context
parameter, but I am unsure why as I have not written that class myself.
To Clarify:
I understand why the error is occurring. The DBAdapter class constructor takes in a context
parameter, and I don't know what to pass in as the context parameter when I'm using it statically. I want the class to be static as I don't want to have to instantiate it every time I want to use it.
I guess my real question would be "why does SQLiteOpenHelper require a context?"