Android 在方法中使用正确的上下文来获取sqlite db

Android 在方法中使用正确的上下文来获取sqlite db,android,sqlite,onclick,android-context,Android,Sqlite,Onclick,Android Context,我基本上是在尝试从另一个类中的sqlite db获取信息。我在onCreate方法中这样做没有任何问题,但是当我试图在onCreate中的onClickListener中使用它时,我找不到正确的上下文来使用。我的代码如下: private AutoCompleteTextView search; private Button showInfoButton; private TextView courseInfo; @Override protected void onCreate(Bundle

我基本上是在尝试从另一个类中的sqlite db获取信息。我在onCreate方法中这样做没有任何问题,但是当我试图在onCreate中的onClickListener中使用它时,我找不到正确的上下文来使用。我的代码如下:

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);
            }
        }
    });
}
我试着把它改成

DataBase db = new DataBase(this.getApplicationContext());


每次我尝试它时,程序都会运行,但当它在else情况下运行时,它会抛出一个错误并关闭。有人能告诉我应该使用什么上下文才能使其运行吗?

由于您可能多次需要数据库连接,我建议在您自己的扩展了
应用程序的应用程序类中打开和关闭数据库连接


这里有onCreate和onDestroy方法,您可以在其中打开和关闭数据库(因为它有一个上下文)。如果将数据库对象设为类变量(public static),则应该能够像使用MyApplication.mDatabase那样使用它,尝试将这行代码放入内部方法>>public void onClick(View v){Context contextNew=getApplicationContext();告诉我它是否有效(我使用此方法访问sqlite dbs)[在主用户界面/活动中创建]从广播接收器和其他无上下文服务中创建,而不是从所述用户界面中调用)将数据库对象存储在一个位置并在多个位置使用,当mulithread使用此对象时,我们会遇到并发问题吗?谢谢:)
DataBase db = new DataBase(this.getApplicationContext());
DataBase db = new DataBase(null);