3

嘿,我在创建 Android 应用程序方面有点菜鸟,这只是我的第二个。我需要创建一个应用程序来扫描条形码并将信息保存到数据库中。

我使用 zxing 条码扫描仪和 Sqllite 数据库创建了一个产品数据库,如本文Zxing 应用程序和 SQLite 数据库中所述。但是,当我在填写产品表格后单击添加产品按钮时。弹出一个消息框说我的应用程序不幸停止了。扫描和填充工作但我认为数据库操作不起作用。

这是我添加产品表单和数据库操作的页面。

开始菜单.java

package com.example.barcodedatabaseapp;

import java.math.BigDecimal;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class StartMenu extends Activity {

    static final class ProductData {
        String barcode;
        String format;
        String title;
        String Others;
        BigDecimal Price;
        }

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_menu);
        Button addButton=(Button) findViewById(R.id.button1);
        addButton.setOnClickListener(new OnClickListener(){
                public void onClick(View v)
                {
                startActivity(new Intent(StartMenu.this,AddProduct.class));
                }

            });

    }


}

添加产品.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.barcodeda  tabaseapp.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);

}
  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 {
                        mProductData.barcode = barcode;
                        mProductData.format = format;
                        mProductData.title = title;
                        mProductData.Price = new BigDecimal(price);

                  mProductDb.insert(mProductData);
                        showInfoDialog(this, "Success", "Product saved successfully");
                        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("Title required\n");
    }

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

    return errors.toString();
    }
}

产品数据库.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="spot_pay.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,")
                            .append("   barcode text,")
                            .append("   format text,")
                            .append("   title text,")
                            .append("   price currency")
                            .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) {
                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());

                return db.insert(PRODUCT_TABLE, null, vals) != -1;
            }
        }

在 xml 文件中有关于硬编码文本字符串的警告,但在 eclipse 中没有错误。

这是 logcat,请注意我的模拟器无法识别我的网络摄像头,我填写了我在兄弟的 Nexus 10 上运行的表格。

06-06 09:26:42.840: E/AndroidRuntime(825): FATAL EXCEPTION: main
06-06 09:26:42.840: E/AndroidRuntime(825): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.google.zxing.client.android.SCAN (has extras) }
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1622)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.app.Activity.startActivityForResult(Activity.java:3370)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.app.Activity.startActivityForResult(Activity.java:3331)
06-06 09:26:42.840: E/AndroidRuntime(825):  at com.example.barcodedatabaseapp.AddProduct.onClick(AddProduct.java:51)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.view.View.performClick(View.java:4202)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.view.View$PerformClick.run(View.java:17340)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.os.Handler.handleCallback(Handler.java:725)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.os.Looper.loop(Looper.java:137)
06-06 09:26:42.840: E/AndroidRuntime(825):  at android.app.ActivityThread.main(ActivityThread.java:5039)
06-06 09:26:42.840: E/AndroidRuntime(825):  at java.lang.reflect.Method.invokeNative(Native Method)
06-06 09:26:42.840: E/AndroidRuntime(825):  at java.lang.reflect.Method.invoke(Method.java:511)
06-06 09:26:42.840: E/AndroidRuntime(825):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-06 09:26:42.840: E/AndroidRuntime(825):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-06 09:26:42.840: E/AndroidRuntime(825):  at dalvik.system.NativeStart.main(Native Method)

06-06 09:28:38.579: E/AndroidRuntime(864): FATAL EXCEPTION: main
06-06 09:28:38.579: E/AndroidRuntime(864): java.lang.NullPointerException
06-06 09:28:38.579: E/AndroidRuntime(864):  at com.example.barcodedatabaseapp.AddProduct.onClick(AddProduct.java:70)
06-06 09:28:38.579: E/AndroidRuntime(864):  at android.view.View.performClick(View.java:4202)
06-06 09:28:38.579: E/AndroidRuntime(864):  at android.view.View$PerformClick.run(View.java:17340)
06-06 09:28:38.579: E/AndroidRuntime(864):  at android.os.Handler.handleCallback(Handler.java:725)
06-06 09:28:38.579: E/AndroidRuntime(864):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-06 09:28:38.579: E/AndroidRuntime(864):  at android.os.Looper.loop(Looper.java:137)
06-06 09:28:38.579: E/AndroidRuntime(864):  at android.app.ActivityThread.main(ActivityThread.java:5039)
06-06 09:28:38.579: E/AndroidRuntime(864):  at java.lang.reflect.Method.invokeNative(Native Method)
06-06 09:28:38.579: E/AndroidRuntime(864):  at java.lang.reflect.Method.invoke(Method.java:511)
06-06 09:28:38.579: E/AndroidRuntime(864):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-06 09:28:38.579: E/AndroidRuntime(864):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-06 09:28:38.579: E/AndroidRuntime(864):  at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

2

您没有mProductDb在 Activity 的onCreate.

mProductDb = new ProductDatabase(this);
于 2013-06-06T16:20:50.087 回答