SQLite 데이터베이스에 테이블을 채우려 고하지만 문제가 발생합니다. 앱이 아닌 Android 스튜디오의 삽입을 통해 수동으로 데이터를 추가하려고합니다. 데이터베이스 어댑터를 만들었으며 여기에서 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;
}
}
먼저 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;
}
도움이 되었기를 바랍니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다