Android 尝试查看数据库时应用程序崩溃

Android 尝试查看数据库时应用程序崩溃,android,database,sqlite,Android,Database,Sqlite,我正在尝试查看外部创建并放入应用程序的SQLite DB中的所有数据。我的代码是由几个教程和我自己的代码组合而成的。在我单击“全部查看”按钮之前,应用程序运行良好。然后,我的LogCat中出现以下错误: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.example.fourth.DBHelper.getAllData()' on a null object

我正在尝试查看外部创建并放入应用程序的SQLite DB中的所有数据。我的代码是由几个教程和我自己的代码组合而成的。在我单击“全部查看”按钮之前,应用程序运行良好。然后,我的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
我目前有两门课:

数据库助手

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.

}
主要活动包括:

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);
    }
}

昨天,我能够使用大部分相同的代码(有一些更改)从虚拟设备一次创建一个DB条目。今天,我试图使用一个外部创建的数据库,并查看其中的3个结果。我知道数据库成功地传输到模拟器,这没有给出任何错误。只有当我单击“查看全部”(昨天工作正常)时,我才会收到一个错误

myDB为空,您尚未将其设置为主活动 替换

DBHelper myDbHelper = new DBHelper(this);

始终使用myDb对象并删除myDbHelper


非常感谢你。修好了,我就跑了!
 myDB = new DBHelper(this);