1

I am working with sqlite database, and if i add an existing item in my database i want it to overwrite and just add 1 in its quantity i know this is possible but i don't know how. can someone help me with this please i will really appreciate it if someone do (Im new in programming) this is for my project*

this is my window for adding an item to data base and show it in listview

public class pop_up extends Activity {
    int qty;


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

        EditText quantity = (EditText)findViewById(R.id.quantity);

        quantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                try{
                    qty = 1;
                }catch(Exception e){

                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try{
                    qty = Integer.valueOf(s.toString()).intValue();
                }catch(Exception e){

                }
            }
        });

        Intent getpop_up = getIntent();

        final int price = getpop_up.getIntExtra("passedprice", 0);
        final String name = getpop_up.getStringExtra("passedname");



        Button add = (Button) findViewById(R.id.add);




        TextView menuprice = (TextView)findViewById(R.id.menuprice);
        String initialprice = String.valueOf(price);
        menuprice.setText(initialprice);

        TextView menuname = (TextView)findViewById(R.id.menuname);
        String currentname = String.valueOf(name);
        menuname.setText(currentname);


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast toast;
                int tprice = ((price)*(qty));

                SQLiteDatabase db = openOrCreateDatabase("Orders.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
                MDB mdb = new MDB(getApplicationContext(), "Orders.db", null, 1);
                db = mdb.getWritableDatabase();
                ContentValues cv = new ContentValues();
                cv.put("Food", name);
                cv.put("Price", tprice);
                cv.put("Quantity", qty);
                db.insert("OrderedList", null, cv);

                toast=Toast.makeText(getApplicationContext(), "Added successfully", Toast.LENGTH_SHORT);

                finish();
                toast.show();
            }


        });

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int width=dm.widthPixels;
        int height = dm.heightPixels;

        getWindow().setLayout((int) (width),(int) (height*.6));



    }
}

this is my listview adapter

public class ListView_Adapter extends ArrayAdapter<String> {
    private final Context context;
    private String[] column1;
    private double[] column2;
    private int[] column3;

    public ListView_Adapter(Context context, String[] column1, double[] column2, int[] column3) {
        super(context, R.layout.list_adapter, column1);
        this.context = context;
        this.column1 = column1;
        this.column2 = column2;
        this.column3 = column3;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_adapter, parent, false);
        }
        TextView t1 = (TextView) convertView.findViewById(R.id.t1);
        TextView t2 = (TextView) convertView.findViewById(R.id.t2);
        TextView t3 = (TextView) convertView.findViewById(R.id.t3);

        t1.setText(column1[position]);
        t2.setText("₱" + column2[position]);
        t3.setText("" + column3[position]);
        return convertView;
    }
} 
jeiidii
  • 87
  • 1
  • 10
  • You should iterate over database before inserting new item. If some unique identifier of your item is matched then don't insert. Also edit your question to **how to overwrite item in database instead of creating new item** – Jibran Khan Aug 26 '15 at 10:03
  • you should provide id for each item and when storing an item into db check for that id and increment the count in db, creating a myItem pojo class containing item_name,item_id will be easier – P-RAD Aug 26 '15 at 10:07
  • 1
    Assign unique ids as mentioned above. Then consider using [Insert or replace](http://stackoverflow.com/questions/3647454/increment-counter-or-insert-row-in-one-statement-in-sqlite) for performance reasons instead of performing round-trip back to your business logic. – Capricorn Aug 26 '15 at 10:46

1 Answers1

3

For my answer I assume you are familiar with the basic concepts of database connections and know how to get results from a database query and execute update queries.

Furthermore I assume you have an sqlite database with a table called table_name from now on and items that have a unique item_name.

So you want to insert items in your database and if they already exist increment their quantity in the table.

Check if the item already exists in your database

Before you can update an item in the database when you insert a new one you should check if it already exists. (assuming the item to be inserted has the name name)

You can do this with a select query like so:

SELECT * FROM table_name WHERE item_name = 'name'

After executing this query you get a result which you can check. There are two actions you would perform thereafter:

  • If the result of the query is empty you know the item does not exist yet and you insert a new item with the initial quantity of 1

  • otherwise you know you want to just update its quantity.

Update the item quantity if it already exists

So now after you know that an item does already exist in your database, you just have to update its quantity. This can be done with the update query: (assuming the item to be inserted has the name name)

UPDATE table_name SET Quantity = Quantity + 1 WHERE item_name = 'name'
Jan
  • 2,025
  • 17
  • 27
  • Unnecessary triggering the DB twice. This approach is good if you want to load the DB item anyway, but when just writing is required, [insert or replace](http://stackoverflow.com/questions/3647454/increment-counter-or-insert-row-in-one-statement-in-sqlite) syntax might be more performant. – Capricorn Aug 26 '15 at 10:49
  • Yes I just upvoted your comment above because I found the link you provided very useful. Anyway this is the approach I went for recently, so I just shared it :). – Jan Aug 26 '15 at 10:55