Search code examples
javaandroidsqlitesqliteopenhelper

Inserting Multiples Records into Two Columns in Sqlite Database using ContentValues



Whenever I use the following code to insert multiple records into a table it only inserts the last initialized value.

Here's the method for inserting data into a table:

public long insertQuote() {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_PHID, 100);
        initialValues.put(KEY_LAT, 28.5700);
        initialValues.put(KEY_LAT, 28.4700);
        initialValues.put(KEY_LAT, 27.1833);
        initialValues.put(KEY_LAT, 26.4583);

        initialValues.put(KEY_LON, 77.3200);
        initialValues.put(KEY_LON, 77.0300);
        initialValues.put(KEY_LON, 78.0167);
        initialValues.put(KEY_LON, 80.3173);

        return db.insert(DATABASE_TABLE, null, initialValues);
    }

In this case for the column key "KEY_LAT" I am only able to see the last initialized value "26.4583" on a S.O.P (Sys.out.println) output on logcat.

Same follows for the other column key "KEY_LON". I can see just these two records.

I suppose they're not inserted into the table as put() Method skips the previously "to-be-inserted" values and accepts the last for a particular column.

Any help is appreciated. Thanks.


Solution

  • This is happening because you are using same key LAT and LON for all. That's being overwritten.

    You should use different keys such as

    public long insertQuote() {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_PHID, 100);
            initialValues.put(KEY_LAT1, 28.5700);
            initialValues.put(KEY_LAT2, 28.4700);
            initialValues.put(KEY_LAT3, 27.1833);
            initialValues.put(KEY_LAT4, 26.4583);
    
            initialValues.put(KEY_LON1, 77.3200);
            initialValues.put(KEY_LON2, 77.0300);
            initialValues.put(KEY_LON3, 78.0167);
            initialValues.put(KEY_LON4, 80.3173);
    
            return db.insert(DATABASE_TABLE, null, initialValues);
        }
    

    Edit:

    So you should use this approach.

    public long insertQuote() {
                ContentValues initialValues = new ContentValues();
                initialValues.put(KEY_PHID, 100);
                initialValues.put(KEY_LAT, 28.5700);
                initialValues.put(KEY_LON, 77.3200);
                db.insert(DATABASE_TABLE, null, initialValues);
                initialValues.put(KEY_LAT, 28.4700);
                initialValues.put(KEY_LON, 77.0300);
                db.insert(DATABASE_TABLE, null, initialValues);
                initialValues.put(KEY_LAT, 27.1833);
                initialValues.put(KEY_LON, 78.0167);
                db.insert(DATABASE_TABLE, null, initialValues);
                initialValues.put(KEY_LAT, 26.4583);
                initialValues.put(KEY_LON, 80.3173);
                return db.insert(DATABASE_TABLE, null, initialValues);  
            }