Shiv
Shiv

Reputation: 129

Getting Exception Index 1 requested, with a size of 1

I am getting exception while fetching data from database in my android project. I am trying to get value of column index 1 from this line of code String ques=c.getString(1);

And this is the code where i am calling database class and trying to fetch database,

try{
c=db.getText(Integer.toString(subid));
    if(c==null)
        return;
    //if(c.getCount()> 0)
    //{
        //int max=c.getCount();
        //int min=0;

        Random rn = new Random();       
        int randomNum =  rn.nextInt(max-1) + rowid;
        c.moveToPosition(randomNum);

        String ques=c.getString(1);
        tv.setText(ques+" ");

        cans=c.getString(2);
        shuffleArray(ans);
        int[] a = new int[4];
        int j=0;
            for (int i = 0; i < ans.length; i++)
            {
              a[j]=ans[i];
              j++;
            }
         ans1=c.getString(a[0]);
         ans2=c.getString(a[1]);
         ans3=c.getString(a[2]);
         ans4=c.getString(a[3]);
         rb1.setText(ans1);
         rb2.setText(ans2);
         rb3.setText(ans3);
         rb4.setText(ans4);
        }

       catch(Exception e)
    {
        Toast.makeText(getApplicationContext(), e.getMessage()+"exception", Toast.LENGTH_LONG).show();
    }

Snap shot of my database content,

enter image description here

this is my database class,

public Cursor getText(String subId) throws SQLException //here it'll get all rows of subId=1 or whatever the value of subId
{
    Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
            KEY_id, KEY_ques, KEY_correctans, KEY_wrongans1,KEY_wrongans2, KEY_wrongans3}, 
            KEY_subjectid + "=" +  " '" + subId + "' " , null,null,null, null,null);
    if (mCursor != null) 
    {
        mCursor.moveToFirst();
    }
    return mCursor;

}

Please help me and hope my question is clear.

Thanks in Advance.

Upvotes: 2

Views: 465

Answers (2)

MMss
MMss

Reputation: 324

Remove c.MovetoPosition(randomno);

Instead try this:

c.moveToFirst();
int rw_cnt=c.getCount();
int rndm = ((Math.random())*10000)%rw_cnt); //generates a random no btwn 1 and rw_cnt
for(int i=0;i<rndm;i++)  //move cursor rand times
c.moveToNext();

This definitely would be slower than c.moveToPostion(); but it wouldn't make much of a difference unless you have thousands of rows

Upvotes: 0

Piotr Chojnacki
Piotr Chojnacki

Reputation: 6867

You have an error:

Index 1 requested, with a size of 1

It says, that the size of your cursor is 1 and you know that indexing starts with 0. Therefore, if you write:

String ques = c.getString(1);

you try to get SECOND element, not the first one. If you want to get first element, you have to write:

String ques = c.getString(0);

Upvotes: 3

Related Questions