android:数据库崩溃我的应用程序。

时间:2014-06-17 13:32:26

标签: android database sqlite

我最近在我的数据库中添加了第三个表格,我用它来做一个测验应用程序。当我尝试使用第三个表进行测验时,它会崩溃应用程序。我很确定问题出在我的DBhelper中,但我不确定在整个班级的哪个方面。

DBHelper类

public class DBHelper extends  SQLiteOpenHelper
{
public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
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 TABLE_QUEST2 = "quest2";
// tasks Table Columns names
private static final String KEY_ID2 = "id";
private static final String KEY_QUES2 = "question"; 
private static final String TABLE_QUEST3 = "quest3";
// tasks Table Columns names
private static final String KEY_ID3 = "id";
private static final String KEY_QUES3 = "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;

@Override
public void onCreate(SQLiteDatabase db) {
dbase=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);
addQuestions();
String sql2 = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST2 + " ( "
        + KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES2
        + " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
        +KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
db.execSQL(sql2);
addQuestions2();
String sql3 = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST3 + " ( "
        + KEY_ID3 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES3
        + " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
        +KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
db.execSQL(sql3);
addQuestions3();
//db.close();
}

private void addQuestions()
{
    Question q1=new Question("8 X 2 " + "=","16", "20", "18", "16");
    this.addQuestion(q1);
    Question q2=new Question("8 X 3  " +    "=", "20", "24", "26", "24");
    this.addQuestion(q2);
    Question q3=new Question("8 X 4 " + " =","30", "35","32","32");
    this.addQuestion(q3);
    Question q4=new Question("8 X 5 " + " = ", "40", "38", "41","40");
    this.addQuestion(q4);
    Question q5=new Question("8 X 6 " +" =","45","48","50","48");
    this.addQuestion(q5);
    Question q6=new Question("8 X 7 " +" =","55","56","58","56");
    this.addQuestion(q6);
    Question q7=new Question("8 X 8 " +" =","64","68","60","64");
    this.addQuestion(q7);
    Question q8=new Question("8 X 9 " +" =","75","72","70","72");
    this.addQuestion(q8);
    Question q9=new Question("8 X 10 " +" =","81","89","80","80");
    this.addQuestion(q9);
    Question q10=new Question("8 X [  ]  " +" = 8","1","9","5","1");
    this.addQuestion(q10);
    Question q11=new Question("8 X [  ] " +" = 24","5","3","6","3");
    this.addQuestion(q11);
    Question q12=new Question("8 X [  ] " +" = 40","6","9","5","5");
    this.addQuestion(q12);
    Question q13=new Question("8 X [  ] " +" = 56","7","8","9","7");
    this.addQuestion(q13);
    Question q14=new Question("8 X [  ] " +" = 80","7","10","9","10");
    this.addQuestion(q14);
}
private void addQuestions2()
{
    Question q1=new Question("2 X 2 " + "=","4", "2", "6", "4");
    this.addQuestion2(q1);
    Question q2=new Question("2 X 3  " +    "=", "7", "6", "5", "6");
    this.addQuestion2(q2);
    Question q3=new Question("2 X 4 " + " =","9", "10","8","8");
    this.addQuestion2(q3);
    Question q4=new Question("2 X 5 " + " = ", "8", "10", "9","10");
    this.addQuestion2(q4);
    Question q5=new Question("2 X 6 " +" =","12","13","11","12");
    this.addQuestion2(q5);
    Question q6=new Question("2 X 7 " +" =","13","14","15","14");
    this.addQuestion2(q6);
    Question q7=new Question("2 X 8 " +" =","16","14","15","16");
    this.addQuestion2(q7);
    Question q8=new Question("2 X 9 " +" =","17","19","18","18");
    this.addQuestion2(q8);
    Question q9=new Question("2 X 10 " +" =","21","19","20","20");
    this.addQuestion2(q9);
    Question q10=new Question("2 X [  ]  " +" = 8","1","4","5","4");
    this.addQuestion2(q10);
    Question q11=new Question("2 X [  ] " +" = 4","2","3","6","2");
    this.addQuestion2(q11);
    Question q12=new Question("2 X [  ] " +" = 10","6","9","5","5");
    this.addQuestion2(q12);
    Question q13=new Question("2 X [  ] " +" = 14","7","8","9","7");
    this.addQuestion2(q13);
    Question q14=new Question("2 X [  ] " +" = 20","7","10","9","10");
    this.addQuestion2(q14);
}
private void addQuestions3()
{
    Question q1=new Question("2 X 2 " + "=","4", "2", "6", "4");
    this.addQuestion2(q1);
    Question q2=new Question("2 X 3  " +    "=", "7", "6", "5", "6");
    this.addQuestion2(q2);
    Question q3=new Question("2 X 4 " + " =","9", "10","8","8");
    this.addQuestion2(q3);
    Question q4=new Question("2 X 5 " + " = ", "8", "10", "9","10");
    this.addQuestion2(q4);
    Question q5=new Question("2 X 6 " +" =","12","13","11","12");
    this.addQuestion2(q5);
    Question q6=new Question("2 X 7 " +" =","13","14","15","14");
    this.addQuestion2(q6);
    Question q7=new Question("2 X 8 " +" =","16","14","15","16");
    this.addQuestion2(q7);
    Question q8=new Question("2 X 9 " +" =","17","19","18","18");
    this.addQuestion2(q8);
    Question q9=new Question("2 X 10 " +" =","21","19","20","20");
    this.addQuestion2(q9);
    Question q10=new Question("8 X 2 " +    "=","16", "20", "18", "16");
    this.addQuestion(q10);
    Question q12=new Question("8 X 3  " +   "=", "20", "24", "26", "24");
    this.addQuestion(q12);
    Question q13=new Question("8 X 4 " +    " =","30", "35","32","32");
    this.addQuestion(q13);
    Question q14=new Question("8 X 5 " +    " = ", "40", "38", "41","40");
    this.addQuestion(q14);
    Question q15=new Question("8 X 6 " +" =","45","48","50","48");
    this.addQuestion(q15);
    Question q16=new Question("8 X 7 " +" =","55","56","58","56");
    this.addQuestion(q16);
    Question q17=new Question("8 X 8 " +" =","64","68","60","64");
    this.addQuestion(q17);
    Question q18=new Question("8 X 9 " +" =","75","72","70","72");
    this.addQuestion(q18);
    Question q19=new Question("8 X 10 " +" =","81","89","80","80");
    this.addQuestion(q19);
}
@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 void addQuestion2(Question quest) {
    //SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_QUES2, 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_QUEST2, null, values);
    }
public void addQuestion3(Question quest) {
    //SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_QUES3, 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_QUEST3, 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 List<Question> getAllQuestions2() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT  * FROM " + TABLE_QUEST2;
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 List<Question> getAllQuestions3() {
    List<Question> quesList = new ArrayList<Question>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_QUEST3;
    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;
}
}

这是调用第三个表的类

public class Combine extends Activity 
{
Random randomGenerator = new Random();
int rand1 = randomGenerator.nextInt(18);
int rand2;
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
Button rda, rdb, rdc;
Button butNext;
MediaPlayer mysound;
boolean loaded=false;
private SoundPool soundPool,soundPool2;
int soundID, soundID2;
private Chronometer chrono;
int timer =60;
String count = "01:00";
@Override
public void onBackPressed() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_combine);
    DBHelper db=new DBHelper(this);
    quesList=db.getAllQuestions3();
    currentQ=quesList.get(rand1);
    txtQuestion=(TextView)findViewById(R.id.textView1);
    rda=(Button)findViewById(R.id.radio0);
    rdb=(Button)findViewById(R.id.radio1);
    rdc=(Button)findViewById(R.id.radio2);
    rda.setOnClickListener(onClickListener);
    rdb.setOnClickListener(onClickListener);
    rdc.setOnClickListener(onClickListener);

    this.chrono = (Chronometer) findViewById(R.id.calling_crono);
    startCrono();
    //butNext=(Button)findViewById(R.id.button1);
    setQuestionView();
    chrono.setOnChronometerTickListener(new OnChronometerTickListener() {

        public void onChronometerTick(Chronometer chronometer) 
        {
            String currentTime= chrono.getText().toString();
            timer --;
            count = "00:"+timer;

            Date date = null;
            try {
                date = new SimpleDateFormat("mm:ss").parse(currentTime);
            }catch (java.text.ParseException e)
            {
                e.printStackTrace();
            }
            String newTime = new SimpleDateFormat("mm:ss").format(date);
            if(newTime.equals("01:00")) 
            {
                chrono.stop();
                Intent intent = new Intent(Combine.this, ResultActivity.class);
                Bundle b = new Bundle();
                int end = -5;
                b.putInt("score", score);
                b.putInt("end", end);
                intent.putExtras(b); 
                soundPool.release();
                soundPool2.release();
                startActivity(intent);
                finish();
             }
        }
    });
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
           @Override
           public void onLoadComplete(SoundPool soundPool, int sampleId,
                   int status) {
               loaded = true;
           }
       });
       soundID = soundPool.load(this, R.raw.correct, 1);
       soundPool2 = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

       soundPool2.setOnLoadCompleteListener(new OnLoadCompleteListener() {
              @Override
              public void onLoadComplete(SoundPool soundPool, int sampleId,
                      int status) {
                  loaded = true;
              }
          });

          soundID2 = soundPool2.load(this, R.raw.error, 1);

}
private OnClickListener onClickListener = new OnClickListener() {
    @Override
    public void onClick(View v)
    {
        int rand2 = randomGenerator.nextInt(18);
        TextView answer = (TextView) v;
        if(currentQ.getANSWER().equals(answer.getText()))
        {
            score++;
            AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
            float actualVolume = (float) audioManager
                      .getStreamVolume(AudioManager.STREAM_MUSIC);
            float maxVolume = (float) audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            float volume = actualVolume / maxVolume;
            soundPool.play(soundID, volume, volume, 1, 0, 1f);
            Log.e("Test", "Played sound");
        }
        else
        {
            AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
            float actualVolume = (float) audioManager
                          .getStreamVolume(AudioManager.STREAM_MUSIC);
            float maxVolume = (float) audioManager
            .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            float volume = actualVolume / maxVolume;

                soundPool2.play(soundID2, volume, volume, 1, 0, 1f);
                Log.e("Test", "Played sound");
        }
        currentQ=quesList.get(rand2);
        setQuestionView();
    }
};
public void startCrono() {
     chrono.setBase(SystemClock.elapsedRealtime());
     chrono.start();
    }
private void setQuestionView()
{
    txtQuestion.setText(currentQ.getQUESTION());
    rda.setText(currentQ.getOPTA());
    rdb.setText(currentQ.getOPTB());
    rdc.setText(currentQ.getOPTC());
    qid++;
}


}

需要它的人的logcat

06-17 14:30:01.238: E/AndroidRuntime(10699): FATAL EXCEPTION: main
06-17 14:30:01.238: E/AndroidRuntime(10699): java.lang.RuntimeException: Unable to   start activity ComponentInfo{com.example/com.example.timestableseasy.Combine}: java.lang.IndexOutOfBoundsException: Invalid index 16, size is 0
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.ActivityThread.access$600(ActivityThread.java:150)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.os.Looper.loop(Looper.java:213)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.ActivityThread.main(ActivityThread.java:5225)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at java.lang.reflect.Method.invokeNative(Native Method)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at java.lang.reflect.Method.invoke(Method.java:525)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at dalvik.system.NativeStart.main(Native Method)
06-17 14:30:01.238: E/AndroidRuntime(10699): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 16, size is 0
06-17 14:30:01.238: E/AndroidRuntime(10699):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at java.util.ArrayList.get(ArrayList.java:308)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at com.example.timestableseasy.Combine.onCreate(Combine.java:54)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at  android.app.Activity.performCreate(Activity.java:5133)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-17 14:30:01.238: E/AndroidRuntime(10699):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2230)
06-17 14:30:01.238: E/AndroidRuntime(10699):    ... 11 more

log cat指出的第54行是

  

quesList = db.getAllQuestions3();           currentQ = quesList.get(RAND 1);

1 个答案:

答案 0 :(得分:1)

您的addQuestion3()方法未向第三个表添加任何内容。它正在添加到第二个和第一个表。因此,当您使用getAllQuestions3()查询第三个表时,它将返回一个空列表,因为第三个表中没有条目。