0

I'm trying to make an android quiz game which contains at least 100 question i found on the net a tutorial that uses DataBase for storing the questions and answers i downloaded the source code and copied the DBHelper.java file to my project and every thing is working fine BUT the problem when i wanted to add a new question my app keep crashes when adding any thing to the database.

package com.example.seenapp;

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) {
    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();
    //db.close();
}
private void addQuestions()
{
    Question q1=new Question("What is JP?","Jalur Pesawat", "Jack sParrow", "Jasa Programmer", "Jasa Programmer");
    this.addQuestion(q1);
    Question q2=new Question("where the JP place?", "Monas, Jakarta", "Gelondong, Bangun Tapan, bantul", "Gelondong, Bangun Tapan, bandul", "Gelondong, Bangun Tapan, bantul");
    this.addQuestion(q2);
    Question q3=new Question("who is CEO of the JP?","Usman and Jack", "Jack and Rully","Rully and Usman", "Rully and Usman" );
    this.addQuestion(q3);
    Question q4=new Question("what do you know about JP?", "JP is programmer home", "JP also realigy home", "all answer is true","all answer is true");
    this.addQuestion(q4);
    Question q5=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
    this.addQuestion(q5);
}
@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;
}
}

it tried coping this code

Question q5=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
    this.addQuestion(q5);

and changing the number to 6 but it not working!! thank you

the logcat before the crash:

04-05 06:15:24.311: E/SoundPool(378): error loading /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.321: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.321: E/SoundPool(378): error loading /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.321: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.331: E/SoundPool(378): error loading /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.331: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.331: E/SoundPool(378): error loading /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.331: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.341: E/SoundPool(378): error loading /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.341: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
04-05 06:15:24.341: E/SoundPool(378): error loading /system/media/audio/ui/KeypressStandard.ogg
04-05 06:15:24.351: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
04-05 06:15:24.351: E/SoundPool(378): error loading /system/media/audio/ui/KeypressSpacebar.ogg
04-05 06:15:24.351: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
04-05 06:15:24.351: E/SoundPool(378): error loading /system/media/audio/ui/KeypressDelete.ogg
04-05 06:15:24.351: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
04-05 06:15:24.361: E/SoundPool(378): error loading /system/media/audio/ui/KeypressReturn.ogg
04-05 06:15:24.361: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
04-05 06:15:24.361: E/SoundPool(378): error loading /system/media/audio/ui/KeypressInvalid.ogg
04-05 06:15:24.361: W/AudioService(378): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
04-05 06:15:24.361: W/AudioService(378): onLoadSoundEffects(), Error -1 while loading samples
04-05 06:15:24.411: D/AndroidRuntime(5083): Shutting down VM
04-05 06:15:24.411: W/dalvikvm(5083): threadid=1: thread exiting with uncaught exception (group=0xb1a43ba8)
04-05 06:15:24.431: E/AndroidRuntime(5083): FATAL EXCEPTION: main
04-05 06:15:24.431: E/AndroidRuntime(5083): Process: com.example.seenjeemapp, PID: 5083
04-05 06:15:24.431: E/AndroidRuntime(5083): java.lang.IllegalStateException: Could not execute method of the activity
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.view.View$1.onClick(View.java:3823)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.view.View.performClick(View.java:4438)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.view.View$PerformClick.run(View.java:18422)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.os.Handler.handleCallback(Handler.java:733)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.os.Looper.loop(Looper.java:136)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at java.lang.reflect.Method.invokeNative(Native Method)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at java.lang.reflect.Method.invoke(Method.java:515)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at dalvik.system.NativeStart.main(Native Method)
04-05 06:15:24.431: E/AndroidRuntime(5083): Caused by: java.lang.reflect.InvocationTargetException
04-05 06:15:24.431: E/AndroidRuntime(5083):     at java.lang.reflect.Method.invokeNative(Native Method)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at java.lang.reflect.Method.invoke(Method.java:515)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at android.view.View$1.onClick(View.java:3818)
04-05 06:15:24.431: E/AndroidRuntime(5083):     ... 11 more
04-05 06:15:24.431: E/AndroidRuntime(5083): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5
04-05 06:15:24.431: E/AndroidRuntime(5083):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at java.util.ArrayList.get(ArrayList.java:308)
04-05 06:15:24.431: E/AndroidRuntime(5083):     at com.example.seenjeemapp.PlayActivity.AnswerCButton(PlayActivity.java:256)
04-05 06:15:24.431: E/AndroidRuntime(5083):     ... 14 more
04-05 06:15:24.471: W/ActivityManager(378):   Force finishing activity com.example.seenjeemapp/.PlayActivity
04-05 06:15:25.041: W/ActivityManager(378): Activity pause timeout for ActivityRecord{b22b2f78 u0 com.example.seenjeemapp/.PlayActivity t70 f}
eyasin
  • 31
  • 5

2 Answers2

0

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5

That's what goes wrong.

at java.util.ArrayList.get(ArrayList.java:308)
at com.example.seenjeemapp.PlayActivity.AnswerCButton(PlayActivity.java:256)

That's where.

Your C button (its event handler) tries to get(5) from an ArrayList of 5 elements.

ArrayLists (like all indexed collections in Java) are indexed from 0, so The Fifth Element (the last one) is indexed under 4, right. It's 0, 1, 2, 3, 4.

This is why you're getting an IndexOutOfBoundsException.

The code causing the error is not within the scope of the code that you posted, so it's hard to pin the bug down, but it looks that the code responsible for handling the C answer (or any other answer, perhaps) is oblivious to the fact that you added question number 6. You must've overlooked something.

I strongly suggest that you learn using Logcat, otherwise you'll always be in the dark whenever you get a critical error.

Some links which could be useful for you here:

Community
  • 1
  • 1
Konrad Morawski
  • 8,307
  • 7
  • 53
  • 91
0

According to your logcat get method on our arraylost is going outofbounds. if your array contains n items get method can only be used with n-1.

I can not see where this get method is used so you should post some more of your code.

other thing why have you commented the line

  SQLiteDatabase db = this.getWritableDatabase();

How can you perform any action without opening a database.

by the way the errors which are causing the application to crash are not in this code

some more tips which might not necessarily cause crashing but you should practice closing and opening your database and cursors at right time and at in correct scopes.

madteapot
  • 2,208
  • 2
  • 19
  • 32