从按钮单击调用方法

时间:2011-02-03 23:25:54

标签: java android

我是java的新手,我试图在点击一个按钮时运行一个方法,我不确定我是否在正确的轨道上。我从Sqlite数据库中选择10个问题,并希望每次单击按钮时循环遍历每个问题0-9。一旦提出所有10个问题,我将转到另一个活动。我有应用程序显示第一个问题很好,但我无法调用showQuestions方法,并在单击按钮并将其传递给方法时将questionNum int增加1。任何帮助将不胜感激!

这是我试图调用的showQuestions方法。

public void showQuestions(Cursor cursor) {
    cursor.moveToPosition(questionNum);
    while (cursor.moveToNext()) {
        // Collect String Values from Query
        StringBuilder questiontxt = new StringBuilder("");
        StringBuilder answertxt1 = new StringBuilder("");
        StringBuilder answertxt2 = new StringBuilder("");
        StringBuilder answertxt3 = new StringBuilder("");
        StringBuilder answertxt4 = new StringBuilder("");
        String question = cursor.getString(2);
        String answer = cursor.getString(3);
        String option1 = cursor.getString(4);
        String option2 = cursor.getString(5);
        String option3 = cursor.getString(6);
        questiontxt.append(question).append("");
        answertxt1.append(answer).append("");
        answertxt2.append(option1).append("");
        answertxt3.append(option2).append("");
        answertxt4.append(option3).append("");
    }
}

这是我正在处理的按钮的代码。有4个按钮。

public void onClick(View v) {
    switch (v.getId()) {

        case R.id.option1_button:
        if (questionNum<9) {
            questionNum ++;
        }
        Questions.this.showQuestions(null);
        break;
    }

这是按钮的XML代码。

<Button
    android:id="@+id/option1_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/option3_button"/>

OnClick Listener for the button

View option1_button = findViewById(R.id.option1_button);
option1_button.setOnClickListener(this);

数据库查询和光标分配

//Get the questions and allocate them to the Cursor
public Cursor getQuestions() {
//Select Query 
String loadQuestions = "SELECT * FROM questionlist ORDER BY QID LIMIT 10";
SQLiteDatabase db = questions.getReadableDatabase();
Cursor cursor = db.rawQuery(loadQuestions, null);
startManagingCursor(cursor);
return cursor;
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

Questions.this.showQuestions(null);

为什么将null传递给showQuestions方法?

让我猜一下 - 它与NullPointerException崩溃。

你尝试过吗? showQuestions(getQuestions())

编辑: 一些一般性的建议:

  • 每次单击按钮时都不会加载问题。

  • 制作一些包含问题所需信息的Question课程

  • 调用onCreate时,打开数据库并在某些Collection中加载所有需要的问题,例如ArrayList<Question>

  • 每次用户点击按钮时,都会从Question获取下一个Collection元素并显示

相关问题