Search code examples
androidsqliteandroid-cursor

Cursor in sqlite remaining in -1 position


I am coding for an android app, I have 3 columns in my database, I have put values into the database using a cursor and I want to retrieve those and display it. But while retrieving it i am getting an exception i.e. CursorIndexOutofBounds Exception, index -1 requested with a size of 1. During debugging i realized that the cursor pointer is not moving at all, even after using methods like moveToFirst(), moveToNext(), it remains in -1 position. Here's my code

Mainactivity.java

public class MainActivity extends ActionBarActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TableLayout t1=(TableLayout)findViewById(R.id.activity_main);
        TableRow tr_head=new TableRow(this);
        tr_head.setId(TableRow.generateViewId());
        tr_head.setBackgroundColor(Color.BLUE);
        tr_head.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT));

        TextView label_bus=new TextView(this);
        label_bus.setId(TextView.generateViewId());
        label_bus.setText("BUS");
        label_bus.setTextColor(Color.WHITE);
        label_bus.setPadding(5, 5, 5, 5);
        tr_head.addView(label_bus);

        TextView label_arrival = new TextView(this);
        label_arrival.setId(TextView.generateViewId());
        label_arrival.setText("Expected Arrival Time");
        label_arrival.setTextColor(Color.WHITE);
        label_arrival.setPadding(5, 5, 5, 5);
        tr_head.addView(label_arrival);

        TextView fare = new TextView(this);
        fare.setId(TextView.generateViewId());
        fare.setText("Fare");
        fare.setTextColor(Color.WHITE);
        fare.setPadding(5, 5, 5, 5);
        tr_head.addView(fare);
        t1.addView(tr_head, new TableLayout.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        try {
            databaseHelper.addFriend("C23", "5 mins", "10");
            databaseHelper.addFriend("DN46", "7 mins", "10");
            databaseHelper.addFriend("C8A", "2 mins", "10");
        }
        catch (SQLException e)
        {
            System.out.println("Exception Caught"+e);
        } 

        MyDatabaseHelper ob=new MyDatabaseHelper(this);
        ob.getFriends().moveToNext();
        int a;
        String b;
        a=ob.getFriends().getColumnCount();
        System.out.println("No. of columns "+a);
        a=ob.getFriends().getCount();
        System.out.println("No. of rows "+a);
        b=ob.getFriends().getColumnName(2);
        System.out.println("The column is "+b);

        boolean c;

        String BUS="",Expected_Arrival_Time="",f="";
        if(ob.getFriends()!=null) {
            System.out.println("Something is present");
            c=ob.getFriends().moveToFirst();
            System.out.println("The truth value is "+c);
            a=ob.getFriends().getColumnIndex("BUS");
            System.out.println("The index of BUS "+a);
            a=ob.getFriends().getColumnIndex("Expected_Arrival_Time");
            System.out.println("The index of expected arrival time "+a);
            a=ob.getFriends().getColumnIndex("Fare");
            System.out.println("The index of Fare "+a);
            System.out.println(ob.getFriends().getCount());
            a=ob.getFriends().getPosition();
            System.out.println("The position of the cursor is "+a);
            c=ob.getFriends().moveToNext();
            System.out.println("Truth value of c "+c);
            a=ob.getFriends().getPosition();
            System.out.println("The position of the cursor is "+a);

            TableRow tr = new TableRow(this);
            tr.setLayoutParams(new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.FILL_PARENT,
                    TableLayout.LayoutParams.WRAP_CONTENT));

            TextView labelBUS = new TextView(this);
            labelBUS.setText(BUS);
            labelBUS.setTextColor(Color.WHITE);
            tr.addView(labelBUS);

            TextView labelARRIVAL = new TextView(this);
            labelARRIVAL.setText(Expected_Arrival_Time);
            labelARRIVAL.setTextColor(Color.WHITE);
            tr.addView(labelARRIVAL);

            TextView labelFARE=new TextView(this);
            labelFARE.setText(f);
            labelFARE.setTextColor(Color.WHITE);
            tr.addView(labelFARE);

            t1.addView(tr, new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.FILL_PARENT,
                    TableLayout.LayoutParams.WRAP_CONTENT));

            if(!ob.getFriends().moveToNext())

        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }
}

MyDatabaseHelper.java

public class MyDatabaseHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME="Bus_Database";

    public MyDatabaseHelper(Context context) 
    {

        super(context,DATABASE_NAME,null,1);
    }

    public void onCreate(SQLiteDatabase database) 
    {
        database.execSQL("CREATE TABLE busdb (BUS TEXT, Expected_Arrival_Time TEXT, Fare INTEGER);");
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        db.execSQL("DROP TABLE IF EXISTS busdb");

        onCreate(db);
    }

    public void addFriend(String BUS,String Expected_Arrival_Time,String fare) throws SQLException
    {
        ContentValues values=new ContentValues(3);

        values.put("BUS", BUS);

        values.put("Expected_Arrival_Time", Expected_Arrival_Time);

        values.put("fare",fare);

        getWritableDatabase().insert("busdb","BUS",values);
    }

    public Cursor getFriends()
    {
        Cursor cursor = getReadableDatabase().query("busdb",new String[] { "BUS", "Expected_Arrival_Time", "Fare"},null, null, null, null, null);
        return cursor;
    }
}

Solution

  •     System.out.println("Something is present");
        c=ob.getFriends().moveToFirst();
        System.out.println("The truth value is "+c);
        a=ob.getFriends().getColumnIndex("BUS");
        System.out.println("The index of BUS "+a);
        a=ob.getFriends().getColumnIndex("Expected_Arrival_Time");
        System.out.println("The index of expected arrival time "+a);
        a=ob.getFriends().getColumnIndex("Fare");
    

    Every time you call getFriends() method you are getting new Cursor. So it is obvious that you can't do nothing with it. Save your cursor in some variable and then work with it.

    Cursor friendsCursor = ob.getFriends();
    if (friendsCursor != null) {
        friendsCursor.moveToFirst();
        // you code
    }