Laurenswuyts
Laurenswuyts

Reputation: 2142

Arraylist not working with android

I got a problem and I can't find it anywhere. So I'am making this quiz app. And I got my mainactivity here:

public class MainActivity extends Activity {

    List<Vragen> quesList;
    int score=0;
    int qid=0;
    Vragen currentQ;
    TextView txtVragen;
    RadioButton rda, rdb, rdc;
    Button butVolgende;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DBHelper db=new DBHelper(this);
        quesList=db.getAllVragen();
        currentQ=quesList.get(qid);
        txtVragen=(TextView)findViewById(R.id.txtVraag);
        rda=(RadioButton)findViewById(R.id.antwoord1);
        rdb=(RadioButton)findViewById(R.id.antwoord2);
        rdc=(RadioButton)findViewById(R.id.antwoord3);
        butVolgende=(Button)findViewById(R.id.btnVolgende);
        setVragenView();
        butVolgende.setOnClickListener(new View.OnClickListener() {     
            public void onClick(View v) {
                RadioGroup grp=(RadioGroup)findViewById(R.id.grpAntwoord);
                RadioButton antwoord=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
                Log.d("yourans", currentQ.getANTWOORD()+" "+antwoord.getText());
                if(currentQ.getANTWOORD().equals(antwoord.getText()))
                {
                    score++;
                    Log.d("score", "Your score"+score);
                }
                if(qid<5){                  
                    currentQ=quesList.get(qid);
                    setVragenView();
                }else{
                    Intent intent = new Intent(MainActivity.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.activity_main, menu);
        return true;
    }
    private void setVragenView()
    {
        txtVragen.setText(currentQ.getVRAAG());
        rda.setText(currentQ.getOPT1());
        rdb.setText(currentQ.getOPT2());
        rdc.setText(currentQ.getOPT3());
        qid++;
    }
}

Here is my DBHelper and the questions are in there:

public class DBHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "DBQuiz";
    // 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_VRAAG = "vraag";
    private static final String KEY_ANTWOORD = "antwoord"; //correct option
    private static final String KEY_OPT1= "opt1"; //option 1
    private static final String KEY_OPT2= "opt2"; //option 2
    private static final String KEY_OPT3= "opt3"; //option 3
    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_VRAAG
                + " TEXT, " + KEY_ANTWOORD+ " TEXT, "+KEY_OPT1 +" TEXT, "
                +KEY_OPT2 +" TEXT, "+KEY_OPT3+" TEXT)";
        db.execSQL(sql);        
        addVragen();
        //db.close();
    }
    private void addVragen()
    {
        Vragen q1=new Vragen("Which company is the largest manufacturer" +
                " of network equipment?","HP", "IBM", "CISCO", "CISCO");
        this.addVraag(q1);
        Vragen q2=new Vragen("Which of the following is NOT " +
                "an operating system?", "SuSe", "BIOS", "DOS", "BIOS");
        this.addVraag(q2);
        Vragen q3=new Vragen("Which of the following is the fastest" +
                " writable memory?","RAM", "FLASH","Register","Register");
        this.addVraag(q3);
        Vragen q4=new Vragen("Which of the following device" +
                " regulates internet traffic?", "Router", "Bridge", "Hub","Router");
        this.addVraag(q4);
        Vragen q5=new Vragen("Which of the following is NOT an" +
                " interpreted language?","Ruby","Python","BASIC","BASIC");
        this.addVraag(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 addVraag(Vragen quest) {
        //SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_VRAAG, quest.getVRAAG()); 
        values.put(KEY_ANTWOORD, quest.getANTWOORD());
        values.put(KEY_OPT1, quest.getOPT1());
        values.put(KEY_OPT2, quest.getOPT2());
        values.put(KEY_OPT3, quest.getOPT3());
        // Inserting Row
        dbase.insert(TABLE_QUEST, null, values);        
    }
    public List<Vragen> getAllVragen() {
        List<Vragen> quesList = new ArrayList<Vragen>();
        // 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 {
                Vragen quest = new Vragen();
                quest.setID(cursor.getInt(0));
                quest.setVRAAG(cursor.getString(1));
                quest.setANTWOORD(cursor.getString(2));
                quest.setOPT1(cursor.getString(3));
                quest.setOPT2(cursor.getString(4));
                quest.setOPT3(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;
    }
}

And here is my Logcat:

08-28 14:33:58.440: W/dalvikvm(21832): threadid=1: thread exiting with uncaught exception (group=0x416e32a0)
08-28 14:33:58.460: E/AndroidRuntime(21832): FATAL EXCEPTION: main
08-28 14:33:58.460: E/AndroidRuntime(21832): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
08-28 14:33:58.460: E/AndroidRuntime(21832):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at java.util.ArrayList.get(ArrayList.java:304)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at com.laurenswuytsjordipapen.cultural.pursuit.MainActivity$1.onClick(MainActivity.java:55)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at android.view.View.performClick(View.java:4262)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at android.view.View$PerformClick.run(View.java:17421)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at android.os.Handler.handleCallback(Handler.java:615)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at android.os.Looper.loop(Looper.java:137)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at android.app.ActivityThread.main(ActivityThread.java:4944)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at java.lang.reflect.Method.invokeNative(Native Method)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at java.lang.reflect.Method.invoke(Method.java:511)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-28 14:33:58.460: E/AndroidRuntime(21832):    at dalvik.system.NativeStart.main(Native Method)

Can anybody please help me I'm stuck and need to get this finished.

Thanks in advance!

Upvotes: 0

Views: 308

Answers (3)

Prateek
Prateek

Reputation: 12252

Can You Please print the logs checking the size, before accessing the list and while returning the list from your getAllVragen method. As you are accessing index 1(means second element) but size is 1 so you should access index 0 .

For ex : Here is my program

import java.util.*;

public class Test{

public static void main(String args[]){

List abc = new ArrayList();
abc.add("Meena");

    System.out.println("list element is : "+abc.get(1));
}

}

In above program my list size is 1 and accessing index 1(i.e 2 element). As a result i got following exception same as yours:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size:
1
        at java.util.ArrayList.rangeCheck(Unknown Source)
        at java.util.ArrayList.get(Unknown Source)
        at Test.main(Test.java:10)

So in short,

nth element in list is represented by index n-1

Upvotes: 0

Venus
Venus

Reputation: 219

TABLE_QUEST table you have only single record your qid is more then the size of your quesList

Check the quesList.size() compare to qid may be qid = 2 array size is 1.

Upvotes: 0

Simon
Simon

Reputation: 6363

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1

Means that you tried to get the second element in an ArrayList that had only one element. So that means that when you do

quesList=db.getAllVragen();

You only get one result

Upvotes: 1

Related Questions