问题
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
回答1:
If you're using eclipse it's beyond child's play. Just make a field somewhere "private Context context" then you go to generate constructor from fields in the source tab. Just spits it out for you. Then when you need to make an instance of the class. Usually "this" in parameters will suffice
EDIT
I hope this helps, I'd rather not prolong a discussion here. in your database:
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public Cursor getDrinks() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DB_NAME, null, null, null, null, null, null);
return cursor;
}
Then in your activity (in oncreate):
private Cursor c;
...
DataBaseHelper drinksDataBase = new DataBaseHelper(this);
c = drinksDataBase.getDrinks();
c.moveToFirst();
回答2:
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.
来源:https://stackoverflow.com/questions/12849930/passing-context-to-sqliteopenhelper