xyz
xyz

Reputation: 71

Why Can't I update the values of the sqlite database

  public void onClick(View v) {

            if (btn66 == v) {
                ContentValues value = new ContentValues();
                value.put(DBhelper.Amount, txtBudget.getText().toString());
                value.put(DBhelper.Description, txr.getText().toString());

                if(DBhelper.Amount == null)
                {
                    db = helper.getWritableDatabase();
                    db.insert(DBhelper.TABLE2, null, value);
                    db.close();
                    clearfield();
                    Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
                    fetchData2();
                    Intent i = new Intent(addbudget.this, MainActivity.class);
                    startActivity(i);

                }
                else{
                    db = helper.getWritableDatabase();
                    db.update(DBhelper.TABLE2, value, "_id "+"="+1, null);
                    db.close();

                    fetchData2();
                    Toast.makeText(this, "Update Successfully", Toast.LENGTH_LONG).show();
                    clearfield();
                }
            }
        }

The above one is my code to add and update values to the sqlite database,after I include the Update method in my code,my add function is not working and my update function also not working.Is there any problem with my code,but I didn't get any error message.

This is my Database tables

     static final String C_ID = "_id";
        static final String Name = "name";
        static final String B_ID = "_id";

        public void onCreate(SQLiteDatabase db){

                db.execSQL("CREATE TABLE " + TABLE1+ "(" +C_ID
                        + " INTEGER PRIMARY KEY AUTOINCREMENT," +Name+ " text unique not null)");

                db.execSQL("CREATE TABLE " + TABLE2+ "(" +B_ID
                        + " INTEGER PRIMARY KEY AUTOINCREMENT," +Description+ " text,"
                        +Amount+ " text, FOREIGN KEY ("+Description+") REFERENCES "+TABLE1+"("+Name+"));");




   }

Upvotes: 1

Views: 102

Answers (1)

pgiitu
pgiitu

Reputation: 1669

Try using something like this to check if a row with the given name is present in the table1:

public boolean checkIfRowPresent(String name) {
    SQLiteDatabase db = helper.getWritableDatabase();

    Cursor cursor =
            db.query(DBhelper.TABLE1, null, DBHelper.NAME + "='" + name + "'", null, null, null,
                    null, null);
    boolean ret = false;
    if (cursor.getCount() > 0) {
        ret = true; // There is a row present in table1 with the given name
    }
    db.close();

    return ret;

}

You should be calling it with this:

checkIfRowPresent(txr.getText().toString())

Let me know if it helps?

Upvotes: 1

Related Questions