调用方法从按钮点击
问题描述:
我是新来的java,我试图运行一个方法,一旦按钮被点击,我不确定我是否在正确的轨道上。我从Sqlite数据库中选择了10个问题,并且每次点击按钮时都希望遍历每个问题0-9。一旦问了所有10个问题,我就会转到另一个活动。我有应用程序显示第一个问题的罚款,但我无法调用showQuestions方法,并在点击按钮并将其传递给方法时增加questionNum int。任何帮助,将不胜感激!调用方法从按钮点击
这是我试图调用的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监听器按钮
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;
}
在此先感谢。
答
Questions.this.showQuestions(null);
为什么将null传递给showQuestions方法?
让我猜 - 它崩溃与NullPointerException
。
你有没有试过 showQuestions(getQuestions())
编辑: 一些一般性的建议:
每次单击该按钮时,不加载的问题。
使包含所有需要的信息的问题
时
onCreate
被调用时,打开数据库并加载一些Collection
所有需要的问题,比如ArrayList<Question>
每次当用户一些
Question
类点击一个按钮,从Collection
获得下一个Question
元素并显示它
`但我在调用showQuestions方法时遇到了问题 - 这非常模糊,有什么症状?它崩溃了吗?它做什么? `showQuestions`运行了吗?你怎么知道的? – 2011-02-03 23:31:59
嘿伯特第一个问题显示正常,但它在按钮单击时崩溃。因此,ShowQuestions在第一次调用时会运行,但在尝试从按钮单击时调用它时,看起来并不是这样。 Thx – Cam 2011-02-03 23:34:51