我的Assets文件夹中有一个SQlite数据库,我的应用程序运行但是当我单击按钮显示复制数据库中的数据时,我的应用程序崩溃

时间:2016-10-31 12:39:44

标签: android nullpointerexception

我是Android编程的新手,请帮助查看我的代码我无法确定当我点击按钮时崩溃的原因。(该按钮应显示从资产中复制的数据库中的数据)

package com.example.atumusiime.mydatabasetrialapplication;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

    DbHelper check;
    Button display;

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

        SQLiteDatabase db = null;
        DbHelper helper = new DbHelper(MainActivity.this);
        helper.onCreate(db);
        show();

    }

    public void show(){
        DbHelper helper = new DbHelper(this);
        helper.open();
        display = (Button)findViewById(R.id.btn_submit);
        display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Cursor res = check.showdata();

                if(res.getCount() == 0) {
                    show_msg("Error","Nothing found");
                    return;
                }
                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()){
                    buffer.append("ID:"+ res.getString(0)+"\n");
                    buffer.append("Name:"+ res.getString(1)+"\n");
                    buffer.append("Date Of Birth:"+ res.getString(2)+"\n\n");
                }
                show_msg("Member Bio Data",buffer.toString());
            }
        });
    }

    public void show_msg(String Tittle, String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(Tittle);
        builder.setMessage(Message);
        builder.show();


    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();


    }

}


package com.example.atumusiime.mydatabasetrialapplication;

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;
import android.widget.Toast;

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

/**
 * Created by atumusiime on 10/31/2016.
 */
public class DbHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "mydb.db";
    public static final int version = 1;
    public static final String product_table = "tblproduct";
    public static final String order_id = "_id";
    public static final String pname = "pname";
    public static final String desc = "desc";
    public static final String quantity = "quantity";
    public static final String rating = "rating";

    private SQLiteDatabase ourdb;
    public Context cont;

    public DbHelper(Context context) {
        super(context, DB_NAME, null, version);
        this.cont = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            File dbFile = cont.getDatabasePath(DB_NAME);
            if (dbFile.exists()){
                Toast.makeText(cont, "Database Already Exist..." , Toast.LENGTH_LONG).show();}
            else{ this.getReadableDatabase();
                InputStream input = cont.getAssets().open(DB_NAME);
                int size = input.available();
                input.close();
                if (size > 0){Log.d("file" , dbFile.getPath());
                    copyDataBase(dbFile);
                    //this.close();
                     } else {
                    // TODO Auto-generated method stub
                    db.execSQL("create table " + product_table +" ( "+ order_id + " INTEGER PRIMARY KEY AUTOINCREMENT , " + pname + " TEXT NOT NULL ," + desc + " TEXT ," + rating + " INTEGER ," + quantity +" INTEGER );");
                    }
                }
            } catch (IOException e) { e.printStackTrace();}
        this.ourdb = db;
    }

    private void copyDataBase(File dbFile) throws IOException {

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

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

        //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);
            Log.d("buf", "" + length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();`enter code here`
        myInput.close();

    }

    public DbHelp`enter code here`er open() throws SQLException
    {
        if (this.ourdb == null)
        {
            this.ourdb = this.getWritableDatabase();
        }

        return this;
    }

    public synchronized void close()
    {
        if(this.ourdb.isOpen())
            this.ourdb.close();
    }
    public long insert(String name, String des, Float ratings, int quan) throws SQLException
    {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(pname, name);
        cv.put(desc, des);
        cv.put(rating, ratings);
        cv.put(quantity, quan);
        return this.ourdb.insertOrThrow(product_table, null, cv);

    }

    public Cursor getAllData() throws SQLException
    {
        // TODO Auto-generated method stub
        String [] colums = new String[]{order_id ,pname ,desc ,rating ,quantity};
        Cursor c = this.ourdb.query(product_table,colums, null, null, null, null, null, null);
        return c;
    }

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

    }

     Cursor showdata(){

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor result = db.rawQuery("SELECT * FROM tblproduct",null);
        return result;
    }
}

我在MainActivity中创建了一个方法show(),它具有onclick listner中按钮的on click监听器,我从我的Dbhelper类调用一个方法然后我尝试在一个警告对话框中显示数据,我已经尝试了所有我知道但猫得到应用程序显示数据我将不胜感激,请帮助

请看我的logcat 10-31 12:32:27.363 921-921 / com.example.atumusiime.mydatabasetrialapplication E / AndroidRuntime:FATAL EXCEPTION:main                                                                                                显示java.lang.NullPointerException                                                                                                    at com.example.atumusiime.mydatabasetrialapplication.MainActivity $ 1.onClick(MainActivity.java:40)                                                                                                    在android.view.View.performClick(View.java:4204)                                                                                                    在android.view.View $ PerformClick.run(View.java:17355)                                                                                                    在android.os.Handler.handleCallback(Handler.java:725)                                                                                                    在android.os.Handler.dispatchMessage(Handler.java:92)                                                                                                    在android.os.Looper.loop(Looper.java:137)                                                                                                    在android.app.ActivityThread.main(ActivityThread.java:5041)                                                                                                    at java.lang.reflect.Method.invokeNative(Native Method)                                                                                                    在java.lang.reflect.Method.invoke(Method.java:511)                                                                                                    在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)                                                                                                    在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)                                                                                                    at dalvik.system.NativeStart.main(Native Method) 10-31 12:37:27.944 921-921 / com.example.atumusiime.mydatabasetrialapplication I / Process:发送信号。 PID:921 SIG:9

1 个答案:

答案 0 :(得分:0)

删除helper.onCreate(db);   这不是必需的。如果要使用标准方式从现有数据库中读取,请参见此处:

http://blog.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

另外还有一种更简单的方法。有一个名为SQLiteAssetHelper的库,它正是为了这个目的而精确简化的。 要了解如何使用SqliteAssetHelper,请阅读此处的官方文档:

https://github.com/jgilfelt/android-sqlite-asset-helper/blob/master/README.markdown