通过文件或适配器填充SQLite数据库

时间:2015-10-27 12:20:01

标签: android sqlite

我正在尝试在我的SQLite数据库中填充一个表但是我遇到了一些麻烦。我试图通过android studio中的插入手动添加数据,而不是在应用程序中。我已经创建了一个数据库适配器,从这里我调用了insertRow命令。

我的应用程序将扫描条形码,然后使用收到的产品名称编号查询数据库。我试图用数字和名称填充条形码数据库。有没有更好的方法来添加下面的数字和名称?因为每次打开这个片段都会再次添加数据

片段

包app.rory.pocket_chef.Fragments;

import android.app.AlertDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.sql.SQLException;

import javax.xml.transform.Result;

import app.rory.pocket_chef.Adapters.Barcodes_Adapter;
import app.rory.pocket_chef.Adapters.DBAdapter;
import app.rory.slidemenu.R;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

/**
 * Created by Rory on 10/22/2014.
 */


public class scan_Foods_Fragment extends Fragment implements ZXingScannerView.ResultHandler{

    private Barcodes_Adapter bar;
    private DBAdapter db;

    private ZXingScannerView scannerView;

    View rootview;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootview = inflater.inflate(R.layout.scan_foods_layout, container, false);

        scannerView = (ZXingScannerView) rootview.findViewById(R.id.scanner_view);
        scannerView.startCamera();
        scannerView.setResultHandler(this);

        return rootview;
    }

    @Override
    public void handleResult(com.google.zxing.Result result) {
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

        alert.setTitle(result.getBarcodeFormat().toString());
        String product = productReturn(result);

        alert.setMessage("You have " + product);
        alert.show();
    }

    //Queries the barcode database for product ID
    public String productReturn(com.google.zxing.Result barcode) {

        //open DB
        try {
            db.open();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        bar.createBarcode(“butter”, 011069001254);
        bar.createBarcode(“milk”, 011056020428);
        bar.createBarcode(“cheese”, 390413010228);
        bar.createBarcode(“ham”, 011069162580);
        bar.createBarcode(“chicken”, 099874147596);
        bar.createBarcode(“thai spice”, 50020768);
        bar.createBarcode(“rice”, 010034514003);
        bar.createBarcode(“soy sauce”, 000111044240);

        //Query DB
        String result = bar.getProduct(barcode);

        //Close DB
        db.close();

        return result;
    }

}

适配器

包app.rory.pocket_chef.Adapters;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.google.zxing.Result;

import java.sql.SQLException;

/**
 * Created by Rory on 06/10/15.
 */
public class Barcodes_Adapter {

    public static final String ROW_ID = "_id";
    public static final String NAME = "name";
    public static final String NUMBER = "number";

    private static final String DATABASE_TABLE = "barcodes";

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DBAdapter.DATABASE_NAME, null, DBAdapter.DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx
     *            the Context within which to work
     */
    public Barcodes_Adapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the public database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException
     *             if the database could be neither opened or created
     */
    public Barcodes_Adapter open() throws SQLException {
        this.mDbHelper = new DatabaseHelper(this.mCtx);
        this.mDb = this.mDbHelper.getWritableDatabase();
        return this;
    }

    /**
     * close return type: void
     */
    public void close() {
        this.mDbHelper.close();
    }

    /**
     * Create a new barcode. If the barcode is successfully created return the new
     * rowId for that barcode, otherwise return a -1 to indicate failure.
     *
     * @param name
     * @param number
     * @return rowId or -1 if failed
     */
    public long createBarcode(String name, int number){
        ContentValues initialValues = new ContentValues();
        initialValues.put(NAME, name);
        initialValues.put(NUMBER, number);
        return this.mDb.insert(DATABASE_TABLE, null, initialValues);
    }



    /**
     * Delete the barcode with the given rowId
     *
     * @param rowId
     * @return true if deleted, false otherwise
     */
    public boolean deleteBarcode(long rowId) {

        return this.mDb.delete(DATABASE_TABLE, ROW_ID + "=" + rowId, null) > 0; //$NON-NLS-1$
    }

    /**
     * Return a Cursor over the list of all barcodes in the database
     *
     * @return Cursor over all barcodes
     */
    public Cursor getAllBarcodes() {

        return this.mDb.query(DATABASE_TABLE, new String[] { ROW_ID,
                NAME, NUMBER }, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the barcode that matches the given rowId
     * @param rowId
     * @return Cursor positioned to matching barcode, if found
     * @throws SQLException if barcode could not be found/retrieved
     */
    public Cursor getBarcode(long rowId) throws SQLException {

        Cursor mCursor =

                this.mDb.query(true, DATABASE_TABLE, new String[] { ROW_ID, NAME,
                        NUMBER}, ROW_ID + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    /**
     * Returns Product name for Barcode number
     * @return String of product
     * @param barcode
     */
    public String getProduct(Result barcode) {

        Cursor result = this.mDb.query(true, DATABASE_TABLE, new String[]{NAME}, NUMBER + "=" + barcode, null, null, null, null, null);

        result.moveToFirst();
        String product = result.getString(result.getColumnIndex("name"));

        return product;

    }

    /**
     * Update the barcode.
     *
     * @param rowId
     * @param name
     * @param number
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateBarcode(long rowId, String name, String number,
                             String year){
        ContentValues args = new ContentValues();
        args.put(NAME, name);
        args.put(NUMBER, number);

        return this.mDb.update(DATABASE_TABLE, args, ROW_ID + "=" + rowId, null) >0;
    }
}

1 个答案:

答案 0 :(得分:0)

<强>首先
注释掉 productReturn()方法中使用的所有createBarcode()行。

public String productReturn(com.google.zxing.Result barcode) {

    //open DB
    try {
        db.open();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    /* comment out this lines
    bar.createBarcode(“butter”, 011069001254);
    bar.createBarcode(“milk”, 011056020428);
    bar.createBarcode(“cheese”, 390413010228);
    bar.createBarcode(“ham”, 011069162580);
    bar.createBarcode(“chicken”, 099874147596);
    bar.createBarcode(“thai spice”, 50020768);
    bar.createBarcode(“rice”, 010034514003);
    bar.createBarcode(“soy sauce”, 000111044240);
                                                  */
    //Query DB
    String result = bar.getProduct(barcode);

    //Close DB
    db.close();

    return result;
}

<强>第二
更改您的 createBarcode()方法代码,如下所示:

public long createBarcode(){
    ContentValues initialValues = new ContentValues();
    initialValues.put(“butter”, 011069001254);
    initialValues.put(“milk”, 011056020428);
    initialValues.put(“cheese”, 390413010228);
    initialValues.put(“ham”, 011069162580);
    initialValues.put(“chicken”, 099874147596);
    initialValues.put(“thai spice”, 50020768);
    initialValues.put(“rice”, 010034514003);
    initialValues.put(“soy sauce”, 000111044240);
    //Similarly you could add new products to the table in future version..
    return this.mDb.insert(DATABASE_TABLE, null, initialValues);
}

<强>第三
如果可能,请在创建条形码表后立即致电 createBarCode()

如果没有,那么您可以在 productReturn()方法中使用 getAllBarcodes(),如下所示,并相应地决定是否调用更改后的createBarcode()方法。

public String productReturn(com.google.zxing.Result barcode) {

    //open DB
    try {
        db.open();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Cursor c = bar.getAllBarCodes();
    if(c.getCount() == 0)
       bar.createBarcode();// we call createBarcode only if value don't exist inside db.

    /* comment out this lines
    bar.createBarcode(“butter”, 011069001254);
    bar.createBarcode(“milk”, 011056020428);
    bar.createBarcode(“cheese”, 390413010228);
    bar.createBarcode(“ham”, 011069162580);
    bar.createBarcode(“chicken”, 099874147596);
    bar.createBarcode(“thai spice”, 50020768);
    bar.createBarcode(“rice”, 010034514003);
    bar.createBarcode(“soy sauce”, 000111044240);
                                                  */
    //Query DB
    String result = bar.getProduct(barcode);

    //Close DB
    db.close();

    return result;
}

希望它有所帮助!