I am working on an app where i would scan a coupon and it would find the matching upc in a sqlite database that i have created and place all of the details from that table into a new table for my personal coupon library. I was getting an error that the database could not be found so I looked here http://stackoverflow.com/questions/16640604/cant-open-database-from-assets-folder-android for help but I am still getting the IOException that yhe database cant be opened. can anyone help? My code is shown below:

scanListener.java

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class scanListener extends Activity{
    private String UPC;
    private String date;
    private int qty;
    SQLiteDatabase db;
    String[] TABLE_COLUMNS = {"UPC","Description", "Discount", "MinReq", "Double", "Image" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scan();

    }

    public void scan(){
        try{
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();
        } catch (ActivityNotFoundException e) {
            // if no scanner is found a prompt to download a scanner will be displayed
            showDialog(scanListener.this, "No scanner found", "Download a Scanner?", "Yes", "No").show();
        }
    }

    //alert dialog to download scanner
    private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence btnYes, CharSequence btnNo){
        AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
        downloadDialog.setTitle(title);
        downloadDialog.setMessage(message);
        downloadDialog.setPositiveButton(btnYes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

                Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");

                Intent intent = new Intent(Intent.ACTION_VIEW, uri);

                try{
                    act.startActivity(intent);
                } catch (ActivityNotFoundException e){ 

                }
            }
        });

        downloadDialog.setNegativeButton(btnNo, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

            }
        });

        return downloadDialog.show();
    }

    //dialog to enter coupon details
    private void couponDetailDialog(){
        final Dialog detailDialog = new Dialog(this);
        detailDialog.setContentView(R.layout.coupondetaildialog);

        //set title for dialog box
        detailDialog.setTitle("Coupon Details:");

        //set textview for expiration date instruction
        TextView text = (TextView) detailDialog.findViewById(R.id.instruction1);
        text.setText("Please enter the expiration date of the coupon:");
        EditText enterDate = (EditText) detailDialog.findViewById(R.id.date);

        //set textview for coupon quantity
        TextView text2 = (TextView) detailDialog.findViewById(R.id.instruction2);
        text2.setText("Please enter the number of coupons:");
        EditText qtyEntry = (EditText) detailDialog.findViewById(R.id.quantity);

        //set up save button
        Button saveButton = (Button) detailDialog.findViewById(R.id.save);
        // if button is clicked, close the custom dialog
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                detailDialog.dismiss();
            }
        });

        //setup cancel button
        Button cancelButton = (Button) detailDialog.findViewById(R.id.cancel);
        // if button is clicked, close the custom dialog
        cancelButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                detailDialog.dismiss();
            }
        });

        detailDialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

        if(scanningResult != null){
            UPC = scanningResult.getContents();
            //search for coupon in database
            Databasehelper dbOpenHelper = new Databasehelper(this);
            db = dbOpenHelper.openDataBase();
            String query = "SELECT * from CouponDatabase where UPC= " + UPC;
            Cursor cursor = db.rawQuery(query, TABLE_COLUMNS);
            cursor.moveToFirst();
            Toast toast = Toast.makeText(getApplicationContext(), 
                    cursor.getString(1), Toast.LENGTH_LONG);
            toast.show();
            couponDetailDialog();

            String scanFormat = scanningResult.getFormatName();
        } else {
            Toast toast = Toast.makeText(getApplicationContext(), 
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

}

Databasehelper.java

    package com.exampsle.extremesavings;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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 Databasehelper extends SQLiteOpenHelper
{
    //Path to the device folder with databases
    public static String DB_PATH = "data/data/com.example.extremesavings/databases/";

     //Database file name
    public static String DB_NAME = "ExtremeSavings";
    private SQLiteDatabase database;
    private final Context context;

     public Databasehelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
    }

     //This piece of code will create a database if it’s not yet created
    public void createDataBase() throws IOException{
        boolean dbExist = checkDataBase();
        if (!dbExist) {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                Log.e(this.getClass().toString(), "Copying error");
                throw new Error("Error copying database!");
            }
        } else {
            Log.i(this.getClass().toString(), "Database already exists");
        }
    }

    private void copyDataBase() throws IOException{
        InputStream input = context.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream output = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while((length = input.read(buffer))>0){
            output.write(buffer, 0, length);
        }
        output.flush();
        output.close();
        input.close();
    }

    //Performing a database existence check
    private boolean checkDataBase() {
        SQLiteDatabase checkDb = null;
        try {
            String path = DB_PATH + DB_NAME;
            checkDb = SQLiteDatabase.openDatabase(path, null,
                          SQLiteDatabase.OPEN_READONLY);
        } catch (SQLException e) {
            Log.e(this.getClass().toString(), "Error while checking db");
            checkDb = null;
        }

        if (checkDb != null) {
            checkDb.close();
        }
        return checkDb != null ? true : false;
    }



    public void openDataBase() throws SQLException {
        String path = DB_PATH + DB_NAME;
        database = SQLiteDatabase.openDatabase(path, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public Cursor sampleHelper(){
        return database.query("TABLE_NAME", null, null, null, null, null, null);
    }

    @Override
    public synchronized void close() {
        if (database != null) {
            database.close();
        }
        super.close();
    }
    @Override
    public void onCreate(SQLiteDatabase db) {}
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}

Btw please excuse the sloppy coding. This is the first full app that I have done that was my own concept.

Edit: i figured out the type mismatch issue but I still cannot open the database.

Recommended Answers

All 3 Replies

Take my advise and use ActiveAndroid library or it new brother Ollie Simple object to object transactions, no need to SQLite boilerplate.

how does it work? This is my first time making an app and its for my senior project in school so it has to work.

I have been looking at a couple of tutorials on it but it only shows how to use it when creating a database but not how to retrieve/manipulate data from an existing database. Does anyone know of any references on how to do this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.