Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an activity in which I am inserting values to a sqlite table, and then querying the table to get the values.

The activity:

public class TableActivity extends Activity {

    TableLayout follow_up_table;
    TableRow followup_tr_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table);

        follow_up_table=(TableLayout) findViewById(R.id.follow_up_table);

        //---------------Essay Title Table Header-----------------------------------------------
        TableRow essay_title_tr_head = new TableRow(this);
        essay_title_tr_head.setId(10);
        essay_title_tr_head.setBackgroundResource(R.drawable.list_header);
        essay_title_tr_head.setLayoutParams(new LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT));


        TextView label_essay_title = new TextView(this);
        label_essay_title.setId(20);
        label_essay_title.setText("Time");
        label_essay_title.setTextColor(Color.WHITE);
        label_essay_title.setPadding(5,5,5,5);
        essay_title_tr_head.addView(label_essay_title);// add the column to the table row here
        label_essay_title.setTextSize(12);    

        TextView label_description = new TextView(this);
        label_description.setId(20);
        label_description.setText("Student Name");
        label_description.setTextColor(Color.WHITE);
        label_description.setPadding(5,5,5,5);
        essay_title_tr_head.addView(label_description);// add the column to the table row here
        label_description.setTextSize(12);    



        follow_up_table.addView(essay_title_tr_head, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

      //---------------Essay Title Table Header-----------------------------------------------

        //getTime();

        // database handler
       insertData("Morning", "2013-04-23 10:00:00", "Suresh Kumar");
       insertData("Morning", "2013-04-23 11:30:00", "Pravat Das");
       insertData("Evening", "2013-04-23 16:16:00", "Namita Roy");
       insertData("Evening", "2013-04-23 17:30:00", "Rakesh Mitra");
       insertData("After noon", "2013-04-23 10:00:00", "Anil Sarma");

       getTime();
    }

    public void getTime()
    {
        // database handler
         // database handler
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());

        // Spinner Drop down elements
        List<String> lables = db.getTime();
        Iterator itr = lables.iterator();
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }

    }

    //method to insert data into local database
    public void insertData(String timeName, String time, String studentName)
    {
        DatabaseHandler db = new DatabaseHandler(TableActivity.this);
        ContentValues values = new ContentValues();
        //db.createDataBase();
         values.put("timeName",timeName);
         values.put("time",time);
         values.put("studentName",studentName);

         db.insertValues(timeName, time, studentName);
        db.close();

    }

}

The database helper class:

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "counselor";

    // Labels table name
    private static final String TABLE_LABELS = "follow_up";

    // Labels Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_time_name = "time_name";
    private static final String KEY_time = "time";
    private static final String KEY_student_name = "student_name";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE follow_up (_id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , time_name VARCHAR, time DATETIME, student_name VARCHAR)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

        // Create tables again
        onCreate(db);
    }

    public void insertValues(String timeName, String time, String studentName)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String sql = "INSERT INTO follow_up ( time_name, time, student_name) VALUES ('"+timeName+"', '"+time+"', '"+studentName+"')";
        Cursor cursor = db.rawQuery(sql, null); //<< execute here 
           cursor.moveToFirst();
           db.close();
    }


// 
//    /**
//     * Getting all labels
//     * returns list of labels
//     * */
    public List<String> getTime(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT time_name FROM follow_up ORDER BY time";

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }
}

The error in logcat:

04-24 09:21:18.187: D/dalvikvm(1260): GC_FOR_ALLOC freed 66K, 7% free 2561K/2748K, paused 169ms, total 183ms
04-24 09:21:18.207: I/dalvikvm-heap(1260): Grow heap (frag case) to 3.222MB for 635812-byte allocation
04-24 09:21:18.328: D/dalvikvm(1260): GC_FOR_ALLOC freed 2K, 6% free 3179K/3372K, paused 116ms, total 116ms
04-24 09:21:18.467: D/dalvikvm(1260): GC_CONCURRENT freed <1K, 6% free 3190K/3372K, paused 9ms+27ms, total 141ms
04-24 09:21:19.167: E/CursorWindow(1260): Failed to read row 0, column 1 from a CursorWindow which has 5 rows, 1 columns.
04-24 09:21:19.167: D/AndroidRuntime(1260): Shutting down VM
04-24 09:21:19.167: W/dalvikvm(1260): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-24 09:21:19.197: E/AndroidRuntime(1260): FATAL EXCEPTION: main
04-24 09:21:19.197: E/AndroidRuntime(1260): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ica.dynamictable/com.ica.dynamictable.TableActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.os.Looper.loop(Looper.java:137)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at java.lang.reflect.Method.invokeNative(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at java.lang.reflect.Method.invoke(Method.java:511)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at dalvik.system.NativeStart.main(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.database.CursorWindow.nativeGetString(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.database.CursorWindow.getString(CursorWindow.java:434)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at com.ica.commons.DatabaseHandler.getTime(DatabaseHandler.java:77)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at com.ica.dynamictable.TableActivity.getTime(TableActivity.java:83)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at com.ica.dynamictable.TableActivity.onCreate(TableActivity.java:73)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.Activity.performCreate(Activity.java:5104)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-24 09:21:19.197: E/AndroidRuntime(1260):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-24 09:21:19.197: E/AndroidRuntime(1260):     ... 11 more

Actually what I am trying to do is to put all time_name into a list so that I can populate a table using it.

Where am I going wrong?

share|improve this question

4 Answers

up vote 1 down vote accepted

In your method of DBHelper getTime(), you are using query for getting only one row. Later in that method you are using labels.add(cursor.getString(1));

you should use labels.add(cursor.getString(0)); instead because there is only one row in the Cursor

share|improve this answer

I think problem is with getter of Cursor class. Everytime you want to fetch data from Cursor use getColumnIndex("columnName") method to avoid typo and numbering errors:

labels.add(cursor.getString(cursor.getColumnIndex("time_name")));

Your problem is that numbering starts from 0 and not from 1. So if you are selecting one column, its order number in query is 0.

This is reason why you are getting Exception.

share|improve this answer
SELECT time_name FROM follow_up ORDER BY time

contains only 1 column. Its index is therefore 0. You'd access it with

labels.add(cursor.getString(0));

Or, more cleanly :

int index = cursor.getColumnIndex("time_name");

and

labels.add(cursor.getString(index));

Also, I should add that your if ... do ... while can be replaced by a single while(cursor.moveToNext()) block, as the position of the newly created cursor is always right before first, making the first moveToNext effetively identical to a moveToFirst

share|improve this answer

cursor.getString(1) should be cursor.getString(0) because in query "SELECT time_name FROM follow_up ORDER BY time"; you will get only one data i.e. time_name at index 0 in cursor.getString(0)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.