【问题标题】:Accessing the external already created database.But the Code isnt working访问外部已创建的数据库。但代码不起作用
【发布时间】:2015-03-31 07:33:22
【问题描述】:

这是我编写的主要活动,但它不起作用!请帮忙

import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
Button button1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1.findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub 
            Toast.makeText(getApplicationContext(),"onClick aaaayaaaa", Toast.LENGTH_LONG).show();

            try {
                MyDatabase db=new MyDatabase(MainActivity.this);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });



    }



}

这是我为访问使用不同应用程序预先填充的外部数据库而编写的 MyDatabase java 文件

import android.database.sqlite.SQLiteException;
import android.widget.Toast;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class MyDatabase extends SQLiteAssetHelper {
 private Context mycontext;
    private String DB_PATH="/mnt/sdcard/Kitchen_Data.db"; 

    private static String DB_NAME = "Kitchen_Data.db";
    public SQLiteDatabase myDataBase;


    public MyDatabase(Context context) throws IOException  {

        super(context,DB_NAME,null,1);
        this.mycontext=context;
        Toast.makeText(mycontext, "Constructor called", Toast.LENGTH_LONG).show();

        boolean dbexist = checkdatabase();
        if (dbexist) {
              opendatabase(); 
        } else {
            System.out.println("Database doesn't exist");
            createdatabase();
        }
    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if(!dbexist) {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch(IOException e) {
                throw new Error("Error copying database");
            }
        }
    }   

    private boolean checkdatabase() {

        boolean checkdb = false;
        try {
            String myPath = DB_PATH;
            File dbfile = new File(myPath);
            Toast.makeText(mycontext, "Database exists", Toast.LENGTH_LONG).show();
            checkdb = dbfile.exists();
        } catch(SQLiteException e) {Toast.makeText(mycontext, "Error in database", Toast.LENGTH_LONG).show();
        }
        return checkdb;
    }

    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;

        //Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(outfilename);

        // transfer byte to inputfile to 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;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
        Toast.makeText(mycontext, "database opeened", Toast.LENGTH_LONG).show();
    }

    public synchronized void close() {
        if(myDataBase != null) {
            myDataBase.close();
        }
        super.close();
    }

}

这是日志:

03-31 12:34:37.045: D/AndroidRuntime(15922): Shutting down VM
03-31 12:34:37.045: W/dalvikvm(15922): threadid=1: thread exiting with uncaught exception (group=0x40d79ae0)
03-31 12:34:37.055: E/AndroidRuntime(15922): FATAL EXCEPTION: main
03-31 12:34:37.055: E/AndroidRuntime(15922): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kitchen_application/com.example.kitchen_application.MainActivity}: java.lang.NullPointerException
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.app.ActivityThread.access$600(ActivityThread.java:145)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.os.Handler.dispatchMessage(Handler.java:99)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.os.Looper.loop(Looper.java:137)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at android.app.ActivityThread.main(ActivityThread.java:5099)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at java.lang.reflect.Method.invokeNative(Native Method)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at java.lang.reflect.Method.invoke(Method.java:511)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
 03-31 12:34:37.055: E/AndroidRuntime(15922):   at dalvik.system.NativeStart.main(Native Method)
03-31 12:34:37.055: E/AndroidRuntime(15922): Caused by: java.lang.NullPointerException
03-31 12:34:37.055: E/AndroidRuntime(15922):    at com.example.kitchen_application.MainActivity.onCreate(MainActivity.java:30)
03-31 12:34:37.055: E/AndroidRuntime(15922):    at android.app.Activity.performCreate(Activity.java:5117)
03-31 12:34:37.055: E/AndroidRuntime(15922):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
03-31 12:34:37.055: E/AndroidRuntime(15922):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
03-31 12:34:37.055: E/AndroidRuntime(15922):    ... 11 more
03-31 12:35:38.650: D/AndroidRuntime(16560): Shutting down VM
03-31 12:35:38.650: W/dalvikvm(16560): threadid=1: thread exiting with uncaught exception (group=0x40d79ae0)
03-31 12:35:38.660: E/AndroidRuntime(16560): FATAL EXCEPTION: main
03-31 12:35:38.660: E/AndroidRuntime(16560): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kitchen_application/com.example.kitchen_application.MainActivity}: java.lang.NullPointerException
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.ActivityThread.access$600(ActivityThread.java:145)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.os.Looper.loop(Looper.java:137)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.ActivityThread.main(ActivityThread.java:5099)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at java.lang.reflect.Method.invokeNative(Native Method)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at java.lang.reflect.Method.invoke(Method.java:511)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at dalvik.system.NativeStart.main(Native Method)
03-31 12:35:38.660: E/AndroidRuntime(16560): Caused by: java.lang.NullPointerException
03-31 12:35:38.660: E/AndroidRuntime(16560):    at com.example.kitchen_application.MainActivity.onCreate(MainActivity.java:30)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.Activity.performCreate(Activity.java:5117)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
03-31 12:35:38.660: E/AndroidRuntime(16560):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
03-31 12:35:38.660: E/AndroidRuntime(16560):    ... 11 more
03-31 12:35:39.982: I/Process(16560): Sending signal. PID: 16560 SIG: 9
03-31 12:36:19.714: D/AndroidRuntime(17185): Shutting down VM
03-31 12:36:19.714: W/dalvikvm(17185): threadid=1: thread exiting with uncaught exception (group=0x40d79ae0)
03-31 12:36:19.794: E/AndroidRuntime(17185): FATAL EXCEPTION: main
03-31 12:36:19.794: E/AndroidRuntime(17185): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kitchen_application/com.example.kitchen_application.MainActivity}: java.lang.NullPointerException
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.ActivityThread.access$600(ActivityThread.java:145)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.os.Looper.loop(Looper.java:137)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.ActivityThread.main(ActivityThread.java:5099)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at java.lang.reflect.Method.invokeNative(Native Method)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at java.lang.reflect.Method.invoke(Method.java:511)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at dalvik.system.NativeStart.main(Native Method)
03-31 12:36:19.794: E/AndroidRuntime(17185): Caused by: java.lang.NullPointerException
03-31 12:36:19.794: E/AndroidRuntime(17185):    at com.example.kitchen_application.MainActivity.onCreate(MainActivity.java:28)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.Activity.performCreate(Activity.java:5117)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
03-31 12:36:19.794: E/AndroidRuntime(17185):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
03-31 12:36:19.794: E/AndroidRuntime(17185):    ... 11 more
03-31 12:36:21.236: I/Process(17185): Sending signal. PID: 17185 SIG: 9

【问题讨论】:

  • 在创建MyDatabase 实例之前,您必须将该数据库复制到您的Path。因为在您的代码中,您正试图从Assets 复制DB。这是错误的
  • 哪一行显示错误?它连接到数据库文件?。
  • 把这个从button1.findViewById(R.id.button1);改为button1 = (Button)findViewById(R.id.button1);也显示错误日志行。
  • 非常感谢 ..:)@Piyush Gupta

标签: android android-sqlite android-assets


【解决方案1】:

在logcat 中没有任何说明错误是因为您的External database。简单的错误在于onCreate() 方法。在您刚刚声明button1 的那个方法上,您需要初始化按钮。所以你需要从

button1.findViewById(R.id.button1);

到

button1 = (Button)findViewById(R.id.button1);

【讨论】:

    【解决方案2】:

    试试这样:

     private static final int DATABASE_VERSION=1;
        private SQLiteDatabase OurDb;
        private final Context myContext;
        private static String DB_PATH = "/data/data/com.example.classroom/databases/";
    
    
    
                /**
                 * 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, DATABASE_NAME, null, 1);
                    this.myContext = context;
                }   
    
              /**
                 * Creates a empty database on the system and rewrites it with your own 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 + DATABASE_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(DATABASE_NAME);
    
                    // Path to the just created empty db
                    String outFileName = DB_PATH + DATABASE_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);
                    }
                     Log.v("log", "copy finish");
                    //Close the streams
                    myOutput.flush();
                    myOutput.close();
                    myInput.close();
    
                }
    
    
    
                @Override
                public synchronized void close() {
    
                        if(OurDb != null)
                            OurDb.close();
    
                        super.close();
    
                }
    
                @Override
                public void onCreate(SQLiteDatabase db) {
    
                }
    
                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
                }
    
                public void openDataBase() throws SQLException{
                    // TODO Auto-generated method stub
                    //Open the database
                    String myPath = DB_PATH + DATABASE_NAME;
                    OurDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    
                }
    
                public void createDataBase()  throws IOException{
                    // TODO Auto-generated method stub
    
                    boolean dbExist = checkDataBase();
    
                    if(dbExist){
                        //do nothing - database already exist
                        Toast.makeText(myContext, "exist", Toast.LENGTH_SHORT).show();
                    }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.
                        Toast.makeText(myContext, "creating", Toast.LENGTH_SHORT).show();
                        this.getReadableDatabase();
                        try {
    
                            copyDataBase();
    
                        } catch (IOException e) {
    
                            Log.v("log",e.toString());
                            throw new Error("Error copying database");
    
    
                        }
                    }
                }
    

    【讨论】:

    • 不要忘记更改包名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    相关资源
    最近更新 更多