将重复数据扫描到android sqlite产品数据库中

时间:2013-06-21 11:21:53

标签: android sqlite insert zxing duplicate-data

我使用zxing创建了一个android产品数据库,如下所示Creating Product Database with zxing barcode scanner adding data to database issue 我修改了页面,以便在扫描产品两次时,应用程序会显示一个消息框,说明产品已经存在,然后不插入。 然而,现在当我扫描产品时,它说应用程序不幸停止了。

以下是修改过的页面

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;

    }
    }

我认为错误是使用ProductDatabase.java中的InsertWithOnConflict语句和赋值。有人可以帮帮我。特别是因为我不清楚所有冲突解决策略及其相应的价值观。如果它是别的东西,请指出它,这是应用程序的最后一部分,它让我疯狂,无法完成它。

1 个答案:

答案 0 :(得分:0)

而不是使用代码:     chk = db.insertWithOnConflict(PRODUCT_TABLE,null,vals,1);

使用此:

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

代码应该完美无缺。

SQLiteDatabase.CONFLICT_IGNORE是我提到的案例的特定冲突解决算法,任何其他算法都会导致错误。