diem_L
diem_L

Reputation: 399

Update SQL Database Columns

I know there has been a lot of these questions, but unfortunately none of these helps me with my problem.

With a button click i want to add some new content to my database, or the existing columns should be overwritten. Adding the content to my database works fine. But if i want to overwrite the existing content, my code just adds a new row to the database.

This is my Code:

Main Activity: Add Content With Button To BD

btnAdd = (Button) findViewById(R.id.btnAdd);
    btnAdd .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ListView shopList= (ListView) findViewById(R.id.lvShopList);


            for(int i = 0; i < dataSource.size();i++){
                tvname = (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvName);
                tvamount= (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvAmount);

                String nameTV = tvname.getText().toString();
                String amaountTV = tvamount.getText().toString();

                ingredient.setName(nameTV);
                ingredient.setAmpunt(amaountTV );
                myDB.getInstance(MainActivity.this).increaseIngredient(ingredient);
            }
        }
    });

This Is My DB Class

public Ingredient increaseIngredient(final Ingredient ingredient){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(COL_NAME, ingredient.getName());
    values.put(COL_AMOUNT, ingredient.getAmount());

    long newID = db.insert(TABLE_NAME, null, values);
    db.close();
    return getiIngredient(newID);

    //Also tried this code, but with this, nothing will be shown:
    // db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(ingredient.getId())});
    // db.close();
    // return getiIngredient(ingredient.getId());
}

public Ingredient getIngredient(final long id){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c = db.query
            (TABLE_NAME, new String[]{KEY_ID, COL_NAME, COL_AMOUNT},
            KEY_ID + " = ?",
            new String[]{String.valueOf(id)},
            null, null, null);

    Ingredient ingredient = null;

    if(c != null && c.getCount() > 0) {
        c.moveToFirst();
        ingredient = new Ingredient(c.getString(c.getColumnIndex(COL_NAME)));
        ingredient.setId(c.getLong(c.getColumnIndex(KEY_ID)));
        ingredient.setAmount(c.getString(c.getColumnIndex(COL_AMOUNT)));
    }
    db.close();
    return ingredient;
}

This Is My Model Class

public class Ingredient implements Serializable {
    private long id;
    private String name;
    private String amount;

    public Zutaten() {
        this(null, null);
    }

    public Zutaten(String name) {
        this(name, null);
    }

    public Zutaten(String name, String amount) {
        this.name = name;
        this.amount= amount;
    }

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount= amount;
    }
}

EDIT: This is my activity where i want to show the DB Content:

public class StorageDB extends AppCompatActivity {
    myDB dbIngredients;

    ListView lvDB;
    TextView name, amount;

    ArrayList<Ingredients> dataSource;
    DbStorageAdapter adapter;

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

        lvDB= (ListView) findViewById(R.id.lvDB);
        dataSource = dbIngredients.getInstance(this).getAllIngredient();

        this.adapter = new DbStorageAdapter (dataSource, this);
        lvDB.setAdapter(adapter);

        name = (TextView)findViewById(R.id.tvName);
        amount= (TextView)findViewById(R.id.tvAmount);

        showDBcontent();
    }

     private void showDBcontent(){
        myDB db = new myDB (this);
        ArrayList<Ingredients> iList = db.getAllIngredient();
        adapter = new DbStorageAdapter (zList, this);
        lvDB.setAdapter(adapter);
     }
}

So if i use update, the listview in my storage activity is empty, and if i use insert all the rows from the database will be shown.

With the first click i add 8 rows to the database. If i use db.insert and click on the button i have 16 rows in my database, and all 16 rows will be shown in the storage activity.

SECOND EDIT:

In fact I just want that my code checks after button click if the table exists. If it exists i want that it will update my table rows. If the table does not exist I want that it insert my content which is send by button click.

I tried this, but it does not work:

public Ingredient increaseIngredient (final Ingredient ingredient ){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c = db.rawQuery
            ("SELECT * FROM " + TABLE_NAME + " WHERE " + COL_NAME + " = ?",
                    null);
    ContentValues values = new ContentValues();

    values.put(COL_NAME, ingredient .getName());
    values.put(COL_AMOUNT, ingredient .getAmount());

   if(c !=null && c.getCount() > 0){
        db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(zutaten.getId())});
        db.close();
        return getZutat(zutaten.getId());
    } else {
        long newID = db.insert(TABLE_NAME, null, values);
        db.close();
        return getZutat(newID);
    }

Upvotes: 0

Views: 72

Answers (1)

forpas
forpas

Reputation: 164139

This:

db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(ingredient.getId())});

would update the row with id = ingredient.getId() if this id exists in the table.
When you call:

myDB.getInstance(MainActivity.this).increaseIngredient(ingredient);

the ingredient object does not contain the id that you want to update.
If you do something like this:

ingredient.setId(10);

prior to calling increaseIngredient() then if there exists a row with id = 10, then this row will be updated.
Edit from comments:
I mean something like this:

public Ingredient increaseIngredient (Ingredient ingredient) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COL_NAME, ingredient.getName());
    values.put(COL_AMOUNT, ingredient.getAmount());

    if (ingredient.getId() == null) {
        long newID = db.insert(TABLE_NAME, null, values);
        db.close();
        return ???;
    } else {
        db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(ingredient.getId())});
        db.close();
        return ???;
    }
}

The question marks mean I don't know what you need to return.

Upvotes: 1

Related Questions