0

我基本上是在尝试从另一个类中的 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 db1 = new DataBase(baseContext);

我试过把它改成

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

DataBase db = new DataBase(null);

并且我尝试的每一种方式,程序都会运行,但是当它出现在 else 情况下时,它会抛出一个错误并关闭。谁能告诉我应该使用什么上下文才能使其运行?

4

1 回答 1

1

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

那里有 onCreate 和 onDestroy 方法,您可以在其中打开和关闭数据库(因为它有上下文)。如果您将数据库对象作为类变量(公共静态),您应该能够像MyApplication.mDatabase.

于 2010-12-13T00:20:57.343 回答