Search code examples
androidsqlitelistviewbarcodezxing

Listing Barcode results Using ZXing (no such column in SQLite )


I really have some troubles since 1 week ago.

I got errors like this :

03-04 14:55:35.690: E/AndroidRuntime(8700): java.lang.RuntimeException: Unable to start activity ComponentInfo{thet.mon.aye/thet.mon.aye.DevilscanActivity}: android.database.sqlite.SQLiteException: no such column: barcodeType: , while compiling: SELECT _id, barcodeType, price FROM notes Please kindly help !!!

I am a beginner Android programmer with Intermediate Java level.

What I am trying to do is to scan the multiple barcodes and list them

So, on my first screen, I got one "scan" button and when I scan the barcodes, the results will be shown below that "scan" button.

I use 2 activities :ListActivity which is main of this program and ZXing activity. I have a SQLite adapter for storing the information of the barcode.

Pseudocode is that ListActivity will call the ZXing Activity, get the barcode result and store it in SQLite database (which is BarcodeDBAdapter in my case)

I have 3 java classes : 1) DevilScanActivity.java for listactivity or main 2) ZXingScan which is the barcode scanning activity 3) BarcodeDBAdapter which is the SQLite database

This is my DevilScanActivity.java

`

package thet.mon.aye;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class DevilscanActivity extends ListActivity {
    /** Called when the activity is first created. */

    private static final int ACTIVITY_CREATE=0;
    private BarcodeDBAdapter mDbHelper;
    private Cursor mNotesCursor;
    private ZxingScan zxscan;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.barcode_list);
        mDbHelper = new BarcodeDBAdapter(this);
        mDbHelper.open();
        fillData();
    // getListView();

        final Button scanButton = (Button) findViewById(R.id.button);
        scanButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {  


               // call ZXingScan on click !
                zxscan.getIntent();
                finish();

            }
        });
    }
    private void fillData() {
        // Get all of the rows from the database and create the item list
        mNotesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(mNotesCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{BarcodeDBAdapter.KEY_BARCODE_TYPE};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter notes = 
            new SimpleCursorAdapter(this, R.layout.barcode_row, mNotesCursor, from, to);
        setListAdapter(notes);
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        l=getListView();
        Cursor c = mNotesCursor;
        c.moveToPosition(position);
        Intent i = new Intent(this, ZxingScan.class);
        i.putExtra(BarcodeDBAdapter.KEY_ROWID, id);
        i.putExtra(BarcodeDBAdapter.KEY_BARCODE_TYPE, c.getString(
                c.getColumnIndexOrThrow(BarcodeDBAdapter.KEY_BARCODE_TYPE)));
        i.putExtra(BarcodeDBAdapter.KEY_PRICE, c.getString(
                c.getColumnIndexOrThrow(BarcodeDBAdapter.KEY_PRICE)));
        startActivityForResult(i, ACTIVITY_CREATE);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Bundle extras = intent.getExtras();
        switch(requestCode) {
            case ACTIVITY_CREATE:
                String title = extras.getString(BarcodeDBAdapter.KEY_BARCODE_TYPE);
                String body = extras.getString(BarcodeDBAdapter.KEY_PRICE);
                mDbHelper.createNote(title, body);
                fillData();
                break;


        }
    }
}

`

This is my ZXingScan.java

    package thet.mon.aye;

import android.app.Activity;
import android.content.Intent;


public class ZxingScan extends Activity {

    private BarcodeDBAdapter barcodedb;
    public void onActivityResult(int requestCode, int resultCode, Intent intent1) {
        intent1 = new Intent("com.google.zxing.client.android.SCAN");
        intent1.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent1, 0);
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent1.getStringExtra("SCAN_RESULT");
                String format = intent1.getStringExtra("SCAN_RESULT_FORMAT");
                 barcodedb.createNote(contents, format);
                 // call DevilscanActivity
                            // Handle successful scan
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
}
}

This is my BarcodeDBAdapter:

package thet.mon.aye;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class BarcodeDBAdapter {

    public static final String KEY_BARCODE_TYPE = "barcodeType";
    public static final String KEY_PRICE = "price";
    public static final String KEY_ROWID = "_id";
    private static final String TAG = "BarCodeDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_CREATE =
        "create table notes (_id integer primary key autoincrement, "
        + "title text not null, body text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 2;
    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

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


    public BarcodeDBAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    public long createNote(String title, String body) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_BARCODE_TYPE, title);
        initialValues.put(KEY_PRICE, body);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteNote(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

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

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_BARCODE_TYPE,
                KEY_PRICE}, null, null, null, null, null);
    }

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

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_BARCODE_TYPE, KEY_PRICE}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateNote(long rowId, String title, String body) {
        ContentValues args = new ContentValues();
        args.put(KEY_BARCODE_TYPE, title);
        args.put(KEY_PRICE, body);

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

================================================================================== After I chaged the following in DatabaseDB class , my SQLite is okay now ! private static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PRICE + " TEXT NOT NULL, " + KEY_BARCODE_TYPE + " TEXT NOT NULL);";

However, don't forget to increment the database version , eg, form 1 to 2 , from 2 to 3 !

but I got nullpointer exception ! help again please

=================================================================================

03-04 18:21:41.640: E/AndroidRuntime(9648): FATAL EXCEPTION: main
03-04 18:21:41.640: E/AndroidRuntime(9648): java.lang.RuntimeException: Unable to start activity ComponentInfo{thet.mon.aye/thet.mon.aye.DevilscanActivity}: java.lang.NullPointerException
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2781)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2797)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.ActivityThread.access$2300(ActivityThread.java:135)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2132)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.os.Looper.loop(Looper.java:143)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.ActivityThread.main(ActivityThread.java:4914)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at java.lang.reflect.Method.invoke(Method.java:521)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at dalvik.system.NativeStart.main(Native Method)
03-04 18:21:41.640: E/AndroidRuntime(9648): Caused by: java.lang.NullPointerException
03-04 18:21:41.640: E/AndroidRuntime(9648):     at thet.mon.aye.DevilscanActivity.onCreate(DevilscanActivity.java:28)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1065)
03-04 18:21:41.640: E/AndroidRuntime(9648):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2745)

Solution

  • By taking a quick look at your code I see that you "select barcodeType", but barcodeType was never defined in your CREATE query. So the column simply cannot be found.