Using the right context inside a method to get an sqlite db
I am basically trying to get information from an sqlite db in another class. I've done this without any problems inside the onCreate method, but when I try to use it inside an onClickListener which is inside that onCreate I cannot find the right context to use. My code is as follows:
private AutoCompleteTextView search;
private Button showInfoButton;
private TextView courseInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_courses);
final Context baseContext = getBaseContext();
courseInfo = (TextView) this.findViewById(R.id.text);
DataBase db = new DataBase(this.getApplicationContext());
db.openDataBase();
final ArrayList<String> aCourses = db.getCoursesArr();
db.close();
search = (AutoCompleteTextView) findViewById(R.id.autocomplete_course);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_courses, aCourses);
search.setAdapter(adapter);
showInfoButton = (Button) this.findViewById(R.id.show_info_button);
showInfoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (aCourses.toString().contains(search.getText()) == false ) {
courseInfo.setText("Please select a course from the drop-down menu and click on the \"Show course information\" button");
}
else{
String selectedCourse = search.toString();
DataBase db1 = new DataBase(baseContext);
db1.openDataBase();
ArrayList<String> courseAttributes = db1.getCourseAttributes();
ArrayList<String> attributeValues = db1.getAttributeValues(selectedCourse);
db1.close();
String courseInformation = "";
for (int i=0; i < courseAttributes.size(); i++){
courseInformation = courseInformation + courseAttributes.get(i) + ": " + attributeValues.get(i) + System.getProperty("line.separator");
}
courseInfo.setText(courseInformation);
}
}
});
}
the problem comes with
DataBase db1 = new DataBase(baseContext);
I've tried changing it to
DataBase db = new DataBase(thi开发者_高级运维s.getApplicationContext());
and
DataBase db = new DataBase(null);
and every way I try it, the program does run, but when it get's in the else case it throws an error and shuts down. Could anyone tell me what context should I use in order to make it run?
As you may need the database connection more than once, I recommend to open and close the database connection in your own application class which extends Application
.
There you have onCreate and onDestroy methods where you can open and close the database (because it has a context). If you make the database object as a class variable (public static) you should be able to use this like MyApplication.mDatabase
.
精彩评论