-3

I am attempting to view all data in an SQLite DB that I created externally and put in my app. The code I have is a conglomeration of a couple tutorials and my own code. The app runs fine until I click the "View All" button. I then get the following error in my LogCat:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.example.fourth.DBHelper.getAllData()' on a null object reference at com.example.fourth.MainActivity$1.onClick

I currently have 2 classes:

DBHelper

package com.example.fourth;

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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

    // The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.fourth/databases/";

    private static String DB_NAME = "bar_info.db";

    private SQLiteDatabase myDataBase;

    private final Context myContext;
    public static final String TABLE_NAME = "bar_info";

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     * 
     * @param context
     */
    public DBHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     */
    public void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();

        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {
                this.close();
                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {

        SQLiteDatabase checkDB = null;

        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {

            // database does't exist yet.

        }

        if (checkDB != null) {

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     */
    private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException {

        // Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

        if (myDataBase != null)
            myDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
        return res;
    }

    // Add your public helper methods to access and get content from the
    // database.
    // You could return cursors by doing "return myDataBase.query(....)" so it'd
    // be easy
    // to you to create adapters for your views.

}

and the MainActivity:

package com.example.fourth;

import android.support.v7.app.ActionBarActivity;

import java.io.IOException;

import android.app.AlertDialog;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    DBHelper myDB;
    EditText editBarName, editBarCity, editDrinkName;
    Button btnAddData, btnViewAll;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DBHelper myDbHelper = new DBHelper(this);
        myDbHelper = new DBHelper(this);

        try {

            myDbHelper.createDataBase();

        } catch (IOException ioe) {

            throw new Error("Unable to create database");

        }

        try {

            myDbHelper.openDataBase();

        } catch (SQLException sqle) {

            throw sqle;
        }

        /*
         * editBarName = (EditText) findViewById(R.id.editBarName); editBarCity
         * = (EditText) findViewById(R.id.editBarCity); editDrinkName =
         * (EditText) findViewById(R.id.editDrinkName); btnAddData = (Button)
         * findViewById(R.id.btnAddData);
         */
        btnViewAll = (Button) findViewById(R.id.btnViewAll);

        // AddData();

        ViewAll();
    }

    /*
     * public void AddData() { btnAddData.setOnClickListener(new
     * View.OnClickListener() {
     * 
     * @Override public void onClick(View v) { boolean isInsterted =
     * myDB.insertData(editBarName.getText().toString(),
     * editBarCity.getText().toString(), editDrinkName.getText().toString()); if
     * (isInsterted == true) Toast.makeText(MainActivity.this, "Data Inserted",
     * Toast.LENGTH_LONG).show(); else Toast.makeText(MainActivity.this,
     * "Data Not Inserted", Toast.LENGTH_LONG).show(); } }); }
     */
    public void ViewAll() {
        btnViewAll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Cursor res = myDB.getAllData();
                if (res.getCount() == 0) {
                    // show message
                    showMessage("Error", "No Data Found");
                    return;
                }

                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()) {
                    buffer.append("ID :" + res.getString(0) + "\n");
                    buffer.append("Bar Name :" + res.getString(1) + "\n");
                    buffer.append("Bar City :" + res.getString(2) + "\n");
                    buffer.append("Drink Name :" + res.getString(3) + "\n\n");

                }
                // Show All Data
                showMessage("Data", buffer.toString());
            }
        });
    }

    public void showMessage(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Yesterday I was able to use much of the same code (there have been some changes) to create a DB one entry at a time from the virtual device. Today I am attempting to use an externally created DB and view the 3 results that I have within it. I know that the DB successfully transferred to the emulator, that gives no error. Only when I click "View all" (which worked fine yesterday) do I get an error

Inessaria
  • 79
  • 1
  • 2
  • 10

1 Answers1

0

myDB is null, you haven't set it Main activity Just replace

DBHelper myDbHelper = new DBHelper(this);

to

 myDB = new DBHelper(this);

use myDb object throughout and remove myDbHelper

UMESH0492
  • 1,701
  • 18
  • 31