Android context from inactivity class

In my SQLite installation class, I have a DbHelper that requires context as part of it. To set the context, I just use the constructor in my SQLite class, which requires context as part of its parameters.

But I just ran into a problem. When I try to call the SQLite class from a class that is not an activity, I cannot use it as context classname.this, and it listens to me.

I also tried to do this to declare a context:

protected Context context;

And then call it this:

SetSql PlayerObject = new SetSql(This.context);

But that didn't work either.

Any suggestion please?

+3
source share
2 answers

pass the application context like this

SetSql PlayerObject = new SetSql(this.getApplicationContext());

Now it should work fine.

+6
public class DBHelper extends SQLiteOpenHelper {

private static final String TAG = "DBHelper";
private static final int DB_VERSION = 1;

private Context context;
private String DB_PATH;
private String DB_NAME;
private String TABLE_NAME;
private boolean booCreate;
private String createString;
private SQLiteDatabase myDataBase;

public DBHelper(Context context, String db_name, String table_name,
        boolean booCreate, String createString) {
    super(context, db_name, null, DB_VERSION);
    this.context = context;
    this.DB_NAME = db_name;
    this.DB_PATH = "/data/data/" + FindPackageName() + "/databases/";
    Log.d(TAG, "DBPATH=" + DB_PATH);
    this.TABLE_NAME = table_name;
    this.createString = createString;
    this.booCreate = booCreate;
    Log.d(TAG,"booCreate=" + String.valueOf(this.booCreate));
    try {
        createDataBase();
    } catch (IOException e) {
        throw new Error("Unable to Create Database");
    }
}

dbHelper = new DBHelper(this, this.getString(R.string.db_name_contact),
            this.getString(R.string.table_name_contacts), true, createString);

III

-1

All Articles