jamian
jamian

Reputation: 1662

Cursor shows 0 values even though data exists in sqlite table

I'm trying to save data in a table and retrieve it immediately in my android app. I'm creating an object of the class and calling insertScriptsArray and fetchScriptsArray in the onCreate

db.insertScriptsArray(scripts);
ArrayList<String> s = db.fetchScriptsArray();

This is my Database helper.class.

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Stocks.db";
private static final int DATABASE_VERSION = 1;

public static final String SCRIPTS_TABLE = "scriptnames";
public static final String COL_SCRIPT_ID = "script_id";
public static final String COL_SCRIPT = "script_name";
public static final String COL_SCRIPT_PRICE = "script_price";


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

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + SCRIPTS_TABLE + "(" +
            COL_SCRIPT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COL_SCRIPT + " TEXT NOT NULL," +
            COL_SCRIPT_PRICE + " REAL NOT NULL)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + SCRIPTS_TABLE);
    onCreate(db);
}

public void insertScriptsArray(ArrayList<String> scripts){
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();

    ContentValues cv = new ContentValues();
    cv.put(COL_SCRIPT_PRICE,0);

    for (String s : scripts){
        cv.put(COL_SCRIPT,s);
        long res = db.insert(SCRIPTS_TABLE,null,cv); //res returns values above -1 always
    }

    db.endTransaction();
    db.close();
}


public ArrayList<String> fetchScriptsArray(){
    ArrayList<String> scripts = new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor c = db.rawQuery("SELECT * FROM " + SCRIPTS_TABLE,null);

    boolean temp = c.moveToFirst(); //temp returns false although data is inserted

    if(temp){
        do{
           scripts.add(c.getString(0));
        }while(c.moveToNext());
    }

    c.close();
    db.close();
    return scripts;

   }

}

Upvotes: 0

Views: 44

Answers (1)

Dave Thomas
Dave Thomas

Reputation: 3837

You are using db.beginTransaction(); in your insertScriptsArray function. You need to call db.setTransactionSuccessful(); before calling db.endTransaction(); if the transaction was successful.

If you don't call db.setTransactionSuccessful(); your changes are rolled back when db.endTransaction(); is called.

Per Android developer docs: https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#beginTransaction()

Upvotes: 1

Related Questions