Question

I created an android product database using zxing as shown here Creating Product Database with zxing barcode scanner adding data to database issue I modified the pages so that when a product is scanned twice the app shows a message box saying product already exists and then doesn't insert. However now when I scan a product, it says the app has unfortunately stopped.

Here are the modified pages

AddProduct.java

package com.example.barcodedatabaseapp;

import java.math.BigDecimal;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.barcodedatabaseapp.StartMenu.ProductData;

public class AddProduct extends Activity implements OnClickListener {

private static final int REQUEST_BARCODE = 0;
private static final ProductData mProductData = new ProductData();
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private Button mScanButton;
private Button mAddButton;
ProductDatabase mProductDb;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_product);
     mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
        mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
        mTitleEdit = (EditText) findViewById(R.id.titleEdit);
        mPriceEdit = (EditText) findViewById(R.id.priceEdit);
        mScanButton = (Button) findViewById(R.id.scanButton);
        mScanButton.setOnClickListener(this);
        mAddButton = (Button) findViewById(R.id.addButton2);
        mAddButton.setOnClickListener(this);
        mProductDb =new ProductDatabase(this); 

}
  public void onClick(View v) {

               switch (v.getId()) {
                case R.id.scanButton:
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    //intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
                    startActivityForResult(intent, REQUEST_BARCODE);
                    break;


                case R.id.addButton2:
                    String barcode = mBarcodeEdit.getText().toString();
                    String format = mFormatEdit.getText().toString();
                    String title = mTitleEdit.getText().toString();
                    String price = mPriceEdit.getText().toString();

                    String errors = validateFields(barcode, format, title, price);
                    if (errors.length() > 0) {
                        showInfoDialog(this, "Please fix errors", errors);
                    } else {

                        //showInfoDialog(this,"Data",barcode);
                        mProductData.barcode = barcode;
                        mProductData.format = format;
                        mProductData.title = title;
                        mProductData.Price = new BigDecimal(price);
                        String DbData=mProductData.barcode.toString();
                        DbData=DbData+"\n"+ mProductData.format.toString();
                        DbData=DbData+"\n"+ mProductData.title.toString();
                        DbData=DbData+"\n"+ mProductData.Price.toString();
                        showInfoDialog(this,"Data",DbData);

                       boolean msg;
                       msg= mProductDb.insert(mProductData);
                       if(msg!=false)
                         {showInfoDialog(this, "Success", "Product saved successfully");
                         resetForm();
                         }
                       else
                       { showInfoDialog(this, "Duplicate!", "Product already exists");
                         resetForm();
                       }


                    }
                    break;
                }   
  }

    private void showInfoDialog(Context context, String title, String information) {
        new AlertDialog.Builder (context)
        .setMessage(information)
        .setTitle(title)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {


            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        }).show();  
    }
    private void resetForm() {
                      mBarcodeEdit.getText().clear();
          mFormatEdit.getText().clear();
          mTitleEdit.getText().clear();
          mPriceEdit.getText().clear();
    }
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_BARCODE) {
            if (resultCode == RESULT_OK) {
                String barcode = intent.getStringExtra("SCAN_RESULT");
                mBarcodeEdit.setText(barcode);

                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                mFormatEdit.setText(format);
            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

private static String validateFields(String barcode, String format, 
    String title, String price) {
    StringBuilder errors = new StringBuilder();

    if (barcode.matches("^\\s*$")) {
        errors.append("Barcode required\n");
    }

    if (format.matches("^\\s*$")) {
        errors.append("Format required\n");
    }

    if (title.matches("^\\s*$")) {
        errors.append("Product Title required\n");
    }

    if (!price.matches("^-?\\d+(.\\d+)?$")) {
        errors.append("Need numeric price\n");
    }

    return errors.toString();
}
}

ProductDatabase.java

package com.example.barcodedatabaseapp;

import java.math.BigDecimal;

import com.example.barcodedatabaseapp.StartMenu.ProductData;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ProductDatabase {
  private static final String PRODUCT_TABLE="products";
  private static final String DATABASE_NAME="ProductsDB45.db";
  private static final int DATABASE_VERSION=1;
private static final BigDecimal ONE_HUNDRED =new BigDecimal(100);

private SQLiteDatabase db;

  private static class ProductDatabaseHelper extends SQLiteOpenHelper {

        private static final String TAG = null;

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

        }

        @Override
        public void onCreate(SQLiteDatabase db) {     
               StringBuilder sql = new StringBuilder();

                sql.append("create table ").append(PRODUCT_TABLE)
                    .append("(  ")
                    .append("   _id integer primary key autoincrement,")
                    .append("   barcode text unique,")
                    .append("   format text,")
                    .append("   title text,")
                    .append("   price currency")
                    //.append("   ,")
                    .append(")  ");

                db.execSQL(sql.toString());    

                Log.d(TAG, PRODUCT_TABLE + "table created");       
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {            
            db.execSQL("drop table if exists " + PRODUCT_TABLE);                    
            onCreate(db);
        }

      }



  public ProductDatabase(Context context) {
        ProductDatabaseHelper helper = new ProductDatabaseHelper(context);
        db = helper.getWritableDatabase();
    }

  public boolean insert(ProductData product) {

        long chk;
        ContentValues vals = new ContentValues();
        vals.put("barcode", product.barcode);
        vals.put("format", product.format);
        vals.put("title", product.title);
        vals.put("price", product.Price.multiply(ONE_HUNDRED).longValue());


      chk=db.insertWithOnConflict(PRODUCT_TABLE, null, vals,1);
        if(chk!= -1)
            return true;
        else
            return false;

    }
    }

The error I think is with the InsertWithOnConflict statement and assignment in ProductDatabase.java. Could Someone please help me out here. Especially as I'm not clear on all the conflict resolution strategies and their corresponding values. If it's something else, please point it out, this is the final part of the App and it's driving me nuts, not being able to complete it.

Was it helpful?

Solution

Instead of using the code: chk=db.insertWithOnConflict(PRODUCT_TABLE, null, vals,1);

Use this:

chk=db.insertWithOnConflict(PRODUCT_TABLE, null, vals,SQLiteDatabase.CONFLICT_IGNORE);

Code should work perfectly.

SQLiteDatabase.CONFLICT_IGNORE is the specific conflict resolution algorithm for the case I mentioned, any other algorithm will cause an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top