Skip to content
Advertisement

Cursor running into error while attempting to read data from SQLite database (Android Studio)

I have been trying to debug this for hours now and I am at a complete dead end. I am creating a program where you enter the current date and your current weight into a screen in Android Studio then click submit. That date gets sent to an SQLite database with two columns for data – “date” and “weight”. There are so many classes and things going on that this is nearly impossible to debug.

I have tried changing variables names, upgrading from SQLite database version 1 to version 2, making sure my sets and gets are working properly… I don’t know what is going on. The errors I get include these main 3… so when I enter date and weight and click submit, i get this logcat error:

E/SQLiteDatabase: Error inserting weight=142 date=07/24/2022
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: weightDataTable.date (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
        at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:961)
        at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:790)
        at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:89)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1868)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1737)
        at com.example.weighttrackerproject.DBHandler.addNewWeight(DBHandler.java:51)
        at com.example.weighttrackerproject.grid$1.onClick(grid.java:50)
        at android.view.View.performClick(View.java:7506)
        at android.view.View.performClickInternal(View.java:7483)
        at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
        at android.view.View$PerformClick.run(View.java:29335)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7898)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

I would a million times appreciate any help. I’m going back and forth trying to figure this out and am so so lost. Also here is my database handler class:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;


public class DBHandler extends SQLiteOpenHelper {

    //Declare variables
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "weightDatabase";

    //Declare table name and columns
    private static final String TABLE_NAME = "weightDataTable";
    private static final String DATE_COL = "date";
    private static final String WEIGHT_COL = "weight";
    private static final String ID_COL = "id";

    //Default constructor
    public DBHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Create query for required columns
        String query = "CREATE TABLE " + TABLE_NAME + "("
                + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + DATE_COL + " TEXT,"
                + WEIGHT_COL + " TEXT)";

        db.execSQL(query);
    }

    //This method is use to add new weight to our sqlite database
    public void addNewWeight(String date, String weightInPounds) {
        //Create new database
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        //Add date and weight values to columns in database
        values.put(DATE_COL, date);
        values.put(WEIGHT_COL, weightInPounds);

        db.insert(TABLE_NAME, null, values);
        //Close the database
        db.close();
    }

    public ArrayList<ReadData> readWeights() {
        //Create new database
        SQLiteDatabase db = this.getReadableDatabase();

        //Create new cursor to query all data in table
        Cursor cursorWeights = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

        //Declare new ArrayList
        ArrayList<ReadData> readWeightsArrayList = new ArrayList<>();

        //Cursor to first position
        if (cursorWeights.moveToFirst()) {
            do {
                //Add cursor data to the arraylist
                readWeightsArrayList.add(new ReadData(cursorWeights.getString(1),
                        cursorWeights.getString(2)));
            } while (cursorWeights.moveToNext());

        }
        //Return the arraylist
        //cursorWeights.close();
        return readWeightsArrayList;
    }

    public void updateWeight(String originalDate, String date, String weight) {

        //Create new db
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        //Put new items into values
        values.put(DATE_COL, date);
        values.put(WEIGHT_COL, weight);


        // on below line we are calling a update method to update our database and passing our values.
        // and we are comparing it with name of our course which is stored in original name variable.
        db.update(TABLE_NAME, values, "date=?", new String[]{originalDate});
        db.close();
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this method is called to check if the table exists already.
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }



}

and ReadData for sets and gets (which is one of the errors) I believe the setter for date might not be working because it is gray while the set for the weight is not gray in the code:

public class ReadData {
    // variables for our coursename,
    // description, tracks and duration, id.
    private String date;
    private String weight;
    private int id;

    // creating getter and setter methods
    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    //Default constructor
    public ReadData(String date, String weight) {
        this.date = date;
        this.weight = weight;

    }
}

Advertisement

Answer

You forgot to add id column

values.put(ID_COL, null);

//By doing an insertion without specifying list of columns, you need a number of values exactly matching the number of columns and must use NULL as a placeholder

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement