Passing Context to SQLiteOpenHelper

James Sunderland picture James Sunderland · Oct 12, 2012 · Viewed 15.3k times · Source

First up, I am new to android apps and am not working solo on this. My team mate has taken design while I handle this, and asked me to set up the database and the method to do this, etc etc.

So while most of this seems to be ok, I put:

Context context = null;
DataBaseHelper drinksDataBase = new DataBaseHelper(context); 

into his main activity.

The constructer is as follows:

public DataBaseHelper(Context  context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
    try{
        createDataBase();
    }
    catch(IOException e){

    }
}

Ignoring the null, which I am assuming is the current cause of the app crashing, how would I go about getting the proper context for the app so that I can make my database work?

It actually seems to be crashing on this.getReadableDatabase() so whether that is the null context or not, I don't know.

Logcat is failing to launch due to:

[2012-10-12 10:37:57 - Unexpected error while launching logcat. Try reselecting the device.] device not found
com.android.ddmlib.AdbCommandRejectedException: device not found
    at com.android.ddmlib.AdbHelper.setDevice(AdbHelper.java:752)
    at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:373)
    at com.android.ddmlib.Device.executeShellCommand(Device.java:462)
    at com.android.ddmuilib.logcat.LogCatReceiver$1.run(LogCatReceiver.java:109)
    at java.lang.Thread.run(Unknown Source)  

Thanks in advance,

James

Answer

Aleksandar Stojadinovic picture Aleksandar Stojadinovic · Oct 12, 2012

Here is what I usually do:

 public class MyApplication extends Application {
    private static MyApplication  instance;
    public MyApplication()
    {
       instance = this;
    }
    public static Context getContext()
    {
       return instance;
    } 

And just set that class into the manifest

 <application
        android:name="my.workspace.MyApplication"
...
 >

After that just call MyApplication.getContext(), where you need it.