尝试启动新活动时,android studio中出现空指针错误,但是我无法锻炼为什么引用为空。我已经尝试了所有可以想到的方法,但数小时内没有任何进展。任何帮助将不胜感激。此外,id都已正确链接,因此并非由于此原因。
请注意,我并不是问一般如何解决它们,而是我的代码有什么具体问题,谢谢。
来自日志的错误消息。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hp.demo, PID: 27961
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hp.demo/com.example.hp.demo.MainActivityQuizBasics}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.hp.demo.Model.QuestionBasics.getQUESTION1()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3037)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.hp.demo.Model.QuestionBasics.getQUESTION1()' on a null object reference
at com.example.hp.demo.MainActivityQuizBasics.setQuestionView(MainActivityQuizBasics.java:176)
at com.example.hp.demo.MainActivityQuizBasics.onCreate(MainActivityQuizBasics.java:107)
at android.app.Activity.performCreate(Activity.java:7149)
at android.app.Activity.performCreate(Activity.java:7140)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
数据库助手-设置sql等。
package com.example.hp.demo.DbHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.hp.demo.Model.QuestionBasics;
import com.example.hp.demo.Model.QuestionChords;
import com.example.hp.demo.Model.QuestionScales;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Quiz.db";
public static final String TABLE_SCORE = "score";
public static final String SCORE_KEY_ID = "id";
public static final String SCORE_KEY_SECTION = "section";
public static final String SCORE_KEY_CAT = "category";
public static final String SCORE_KEY_SCORE = "score";
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 static final String KEY_OPTD = "optd"; //option d
private static final String KEY_CAT = "category"; //category
private static final String TABLE_QUEST = "questScales";
public static final String TABLE_QUEST1 = "questBasics";
private static final String TABLE_QUEST2 = "questChords";
private SQLiteDatabase db;
// public DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, 1);
// }
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
String basicsTableCreate = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST1 + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT, " + KEY_OPTD + " TEXT, " + KEY_CAT + " TEXT)";
db.execSQL(basicsTableCreate);
addQuestionsBasics(db);
String scoresTableCreate = "CREATE TABLE IF NOT EXISTS " + TABLE_SCORE + " ( "
+ SCORE_KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SCORE_KEY_SECTION
+ " TEXT, " + SCORE_KEY_CAT + " TEXT, " + SCORE_KEY_SCORE + " INTEGER)";
db.execSQL(scoresTableCreate);
}
private void addQuestionsBasics(SQLiteDatabase db) {
QuestionBasics q101 = new QuestionBasics("What is pitch?", "The length of a sound", "The overall quality of a sound", "The highness or lowness of a sound", "The volume of a sound", "The highness or lowness of a sound", "B");
this.addQuestionBasics(q101,db);
QuestionBasics q102 = new QuestionBasics("What is 'timbre'?", "The ove", "format it", "compile it", "hardware it", "format it", "B");
this.addQuestionBasics(q102,db);
QuestionBasics q103 = new QuestionBasics("What is rhythm?", "The sound a metronome makes", "The organisation of music through time", "A beat that repeats itself", "The amount of beats in a bar", "The organisation of music through time", "B");
this.addQuestionBasics(q103,db);
QuestionBasics q104 = new QuestionBasics("What is harmony?", "A series of pitches creating a musical statement", "The result of multiple notes played simultaneously", "A strong match between 2 different notes", "The sound a chord makes when the notes are in the correct key", "A strong match between 2 different notes", "B");
this.addQuestionBasics(q104,db);
QuestionBasics q105 = new QuestionBasics("What is a 'melody'?", "A strong rhythm that keeps the tune going", "A series of pitches that form a musical statement", "A set of chords that works well together", "A short motif to transition 2 sections of a song", "A series of pitches that form a musical statement", "B");
this.addQuestionBasics(q105,db);
QuestionBasics q106 = new QuestionBasics("What is 'dynamics'?", "Changes in textures, such as switching instruments", "Variations in loudness and softness", "The movement of music between different keys", "The way the melody of a song integrates with the chords", "Variations in loudness and softness", "B");
this.addQuestionBasics(q106,db);
QuestionBasics q107 = new QuestionBasics("What two note note pairs have no sharp or flat between them?", "DE, AB", "DF, BC", "BC ,DE", "EF, BC", "EF, BC", "B");
this.addQuestionBasics(q107,db);
}
public void addQuestionsBasics(QuestionBasics quest) {
addQuestionBasics(quest,this.getWritableDatabase());
}
public void addQuestionBasics(QuestionBasics quest,SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_QUES, quest.getQUESTION1());
contentValues.put(KEY_ANSWER, quest.getANSWER1());
contentValues.put(KEY_OPTA, quest.getOPTA1());
contentValues.put(KEY_OPTB, quest.getOPTB1());
contentValues.put(KEY_OPTC, quest.getOPTC1());
contentValues.put(KEY_OPTD, quest.getOPTD1());
contentValues.put(KEY_CAT, quest.getCATEGORY1());
// Inserting Row
db.insert(TABLE_QUEST1, null, contentValues);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);
onCreate(db);
}
public List<QuestionBasics> getAllQuestions1(String tname, String lname) {
List<QuestionBasics> quesList1 = new ArrayList<QuestionBasics>();
String selectQuery1 = "SELECT * FROM " + tname + " WHERE " + KEY_CAT + " = '" + lname + "'";
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionBasics quest1 = new QuestionBasics();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
// return quest list
return quesList1;
}
public boolean insertScoreBasics(int scoreBasics, String tname, String cname) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SCORE_KEY_SECTION, tname);
contentValues.put(SCORE_KEY_CAT, cname);
contentValues.put(SCORE_KEY_SCORE, scoreBasics);
long resultscore = db.insert(TABLE_SCORE, null, contentValues);
if (resultscore == -1)
return false;
else
return true;
}
public int getScoreBasics() {
Cursor c;
SQLiteDatabase db = this.getWritableDatabase();
String sqlSelectQuery = "SELECT MAX(" + SCORE_KEY_SCORE + ") FROM " + TABLE_SCORE + " WHERE " + SCORE_KEY_SECTION + " = '" + TABLE_QUEST1 + "' AND " + SCORE_KEY_CAT + " = " + "'I'";
c = db.rawQuery(sqlSelectQuery, null);
c.moveToFirst();
int x = c.getInt(0);
return x;
}
}
测验活动Java类
package com.example.hp.demo;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.hp.demo.DbHelper.DatabaseHelper;
import com.example.hp.demo.Model.QuestionBasics;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivityQuizBasics extends AppCompatActivity {
private static final String TAG = "QuizActivity";
public int score = 0;
public ArrayList<String> wrongQuestListBasics = new ArrayList<String>();
public ArrayList<String> selectedBasics = new ArrayList<String>();
public ArrayList<String> actualAnswerBasics = new ArrayList<String>();
List<QuestionBasics> quesList1 = new ArrayList<>();
int ctr1 = 1;
QuestionBasics currentQ1;
TextView txtQuestion1;
RadioGroup grp;
RadioButton rda1, rdb1, rdc1, rdd1;
Button butNext1;
Random random1 = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
TextView textViewTime1;
int number;
ProgressBar progressBar;
int progress = 1;
String tableName = "", catName = "";
TextView qstnNo;
DatabaseHelper mDBHlpr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions_basics);
mDBHlpr = new DatabaseHelper(this, "blah blah blah", null, 1);
QuestionBasics myQuestion = new QuestionBasics(
"What is note X?",
"It's not a note",
"A note that only xylophones can make.",
"A note when a bowed instrument is played with two bows",
"A synthesised x wave", "It's not a note",
"Basics");
mDBHlpr.addQuestionsBasics(myQuestion);
List<QuestionBasics> mylist = mDBHlpr.getAllQuestions1(DatabaseHelper.TABLE_QUEST1, "doesnotmatter");
for (QuestionBasics q : mylist) {
Log.d("QUESTIONS", q.getQUESTION1());
}
qstnNo = findViewById(R.id.qstnNo);
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
tableName = (String) b.get("table_name");
catName = (String) b.get("level_name");
Log.d("Table Name", tableName);
Log.d("Level Name", catName);
}
number = 0;
//DatabaseHelper db = new DatabaseHelper(this);
//db.addBasicsTable(tableName,catName);
//timer
textViewTime1 = findViewById(R.id.textViewTime);
final CounterClass timer = new CounterClass(1800000, 1000);
timer.start();
quesList1 = mDBHlpr.getAllQuestions1("questBasics", catName);
for (int i = 0; i < 50; i++) {
while (true) {
int next = random1.nextInt(50);
if (!list.contains(next)) {
list.add(next);
break;
}
}
}
//layout content
currentQ1 = quesList1.size() == 0 ? null :quesList1.get(0);
txtQuestion1 = findViewById(R.id.textView1);
rda1 = findViewById(R.id.radio0);
rdb1 = findViewById(R.id.radio1);
rdc1 = findViewById(R.id.radio2);
rdd1 = findViewById(R.id.radio3);
butNext1 = findViewById(R.id.button1);
setQuestionView();
grp = findViewById(R.id.radioGroup1);
butNext1.setEnabled(false);
grp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if (i == R.id.radio0 || i == R.id.radio1 || i == R.id.radio2 || i == R.id.radio3)
butNext1.setEnabled(true);
}
});
progressBar = findViewById(R.id.progressBar);
progressBar.setMax(30);
progressBar.setProgress(1);
//checking answer
butNext1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentQ1 == null){
Log.e(TAG,"no q in database");
return;
}
progress = progress + 1;
progressBar.setProgress(progress);
RadioButton answer = findViewById(grp.getCheckedRadioButtonId());
//Log.d("yourans", currentQ1.getANSWER1() + " " + answer.getText());
if (currentQ1.getANSWER1().equals(answer.getText())) {
score++;
//Log.d("score", "Your score" + score1);
} else {
wrongQuestListBasics.add(number, currentQ1.getQUESTION1());
selectedBasics.add(number, answer.getText().toString());
actualAnswerBasics.add(number, currentQ1.getANSWER1());
number++;
}
grp.clearCheck();
butNext1.setEnabled(false);
//finishing quiz
if (ctr1 < 31) {
if (ctr1 == 30) {
butNext1.setText("End Quiz");
}
currentQ1 = quesList1.get(list.get(ctr1));
setQuestionView();
} else {
timer.onFinish();
timer.cancel();
}
}
});
}
public void showResult() {
Intent intent = new Intent(MainActivityQuizBasics.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("scoreBasics", score);//Your score
b.putString("section", "questBasics");//Your table name
b.putString("category", catName);//Your category name
intent.putStringArrayListExtra("wrongQuestions", wrongQuestListBasics);
intent.putStringArrayListExtra("selectedAnswer", selectedBasics);
intent.putStringArrayListExtra("actualAnswer", actualAnswerBasics);
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
private void setQuestionView() {
txtQuestion1.setText(currentQ1.getQUESTION1());
rda1.setText(currentQ1.getOPTA1());
rdb1.setText(currentQ1.getOPTB1());
rdc1.setText(currentQ1.getOPTC1());
rdd1.setText(currentQ1.getOPTD1());
if (ctr1 < 10)
qstnNo.setText("0" + ctr1 + "/30");
else
qstnNo.setText("" + ctr1 + "/30");
ctr1++;
}
}
}