我想在我的应用中加入一个小测验。为了测试一下,我尝试了一个作为答案列出的变体。我的主要活动是一个选择器,通过按钮显示所有选项。该应用程序使用一个名为eGREp.db的数据库来提供诸如含义,单词列表等功能。由于该部分工作得很好,我想创建一个新的数据库并单独工作。点击测试时,应该启动测验活动。
我已将onClick()字段设置为指向openQuiz,其中包含以下内容
public void openQuiz(View view) {
// Do something in response to button
Intent intent = new Intent(this, Quiz.class);
startActivity(intent);
}
现在应该启动测验活动,但是几乎没有例外。 测验班
package com.example.egrep;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Quiz extends Activity {
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext=(Button)findViewById(R.id.button1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DbHelper db = new DbHelper(Quiz.this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radioButton0);
rdb=(RadioButton)findViewById(R.id.radioButton1);
rdc=(RadioButton)findViewById(R.id.radioButton2);
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<5){
currentQ=quesList.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(Quiz.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
}
显示错误
03-18 15:37:13.834: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException
03-18 15:37:13.834: E/AndroidRuntime(1201): at com.example.egrep.DbHelper.addQuestion(DbHelper.java:67)
03-18 15:37:13.834: E/AndroidRuntime(1201): at com.example.egrep.DbHelper.onCreate(DbHelper.java:35)
03-18 15:37:13.834: E/AndroidRuntime(1201): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
03-18 15:37:13.834: E/AndroidRuntime(1201): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
03-18 15:37:13.834: E/AndroidRuntime(1201): at com.example.egrep.DbHelper.getAllQuestions(DbHelper.java:73)
03-18 15:37:13.834: E/AndroidRuntime(1201): at com.example.egrep.Quiz.onCreate(Quiz.java:29)
03-18 15:37:13.834: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5133)
03-18 15:37:13.834: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-18 15:37:13.834: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
问题类
package com.example.egrep;
public class Question {
private int ID;
private String QUESTION;
private String OPTA;
private String OPTB;
private String OPTC;
private String ANSWER;
public Question()
{
ID=0;
QUESTION="";
OPTA="";
OPTB="";
OPTC="";
ANSWER="";
}
public Question(String qUESTION, String oPTA, String oPTB, String oPTC,
String aNSWER) {
QUESTION = qUESTION;
OPTA = oPTA;
OPTB = oPTB;
OPTC = oPTC;
ANSWER = aNSWER;
}
public int getID()
{
return ID;
}
public String getQUESTION() {
return QUESTION;
}
public String getOPTA() {
return OPTA;
}
public String getOPTB() {
return OPTB;
}
public String getOPTC() {
return OPTC;
}
public String getANSWER() {
return ANSWER;
}
public void setID(int id)
{
ID=id;
}
public void setQUESTION(String qUESTION) {
QUESTION = qUESTION;
}
public void setOPTA(String oPTA) {
OPTA = oPTA;
}
public void setOPTB(String oPTB) {
OPTB = oPTB;
}
public void setOPTC(String oPTC) {
OPTC = oPTC;
}
public void setANSWER(String aNSWER) {
ANSWER = aNSWER;
}
}
DbHelper类
package com.example.egrep;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "triviaQuiz";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; //correct option
private static final String KEY_OPTA= "opta"; //option a
private static final String KEY_OPTB= "optb"; //option b
private static final String KEY_OPTC= "optc"; //option c
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
db.execSQL(sql);
Question q1=new Question("Choose the correct alternative that will continue the same pattern and replace the question mark in the given series." +
" 120, 99, 80, 63, 48, ?","35", "38", "39", "A");
this.addQuestion(q1);
Question q2=new Question("A, P, R, X, S and Z are sitting in a row. S and Z are in the centre. A and P are at the " +
"ends. R is sitting to the left of A. Who is to the right of P ?", "A", "X", "S", "B");
this.addQuestion(q2);
Question q3=new Question("Which of the following is the fastest" +
" writable memory?","RAM", "FLASH","Register","C");
this.addQuestion(q3);
Question q4=new Question("Which of the following device" +
" regulates internet traffic?", "Router", "Bridge", "Hub","A");
this.addQuestion(q4);
Question q5=new Question("Which of the following is NOT an" +
" interpreted language?","Ruby","Python","BASIC","C");
this.addQuestion(q5);
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
// Create tables again
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest) {
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
// Inserting Row
dbase.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return quesList;
}
public int rowcount()
{
int row=0;
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row=cursor.getCount();
return row;
}
}
你能帮助我理解为什么抛出这些异常以及上面的代码有什么问题。
答案 0 :(得分:1)
由于您在创建任何视图之前初始化butNext
按钮,因此butNext
按钮未正确初始化。
现在,在butNext
方法中初始化onCreate()
...
Button butNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
butNext=(Button)findViewById(R.id.button1);
}
答案 1 :(得分:1)
您需要在setContentView
之后初始化onCreate中的按钮Button butNext=(Button)findViewById(R.id.button1);
作为
Button butNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
butNext=(Button)findViewById(R.id.button1);
}
findViewById
在当前视图层次结构中查找视图。您需要先设置布局的内容,然后初始化视图。
答案 2 :(得分:1)
Button butNext=(Button)findViewById(R.id.button1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
您需要在夸大布局后检索Button
,否则findViewById
会返回null
。所以它应该是
Button butNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz); //layout inflated, now you can get your elements
butNext=(Button)findViewById(R.id.button1);
还要学习从logcat中读取。你会发现你的错误比在这里提出问题要快得多。以下是重要的部分:
Caused by: java.lang.NullPointerException
03-18 14:41:31.194: E/AndroidRuntime(901): at android.app.Activity.findViewById(Activity.java:1853)
03-18 14:41:31.194: E/AndroidRuntime(901): at com.example.egrep.Quiz.<init>(Quiz.java:20)