Android从预构建的SQLite数据库中获取数据

时间:2014-08-09 19:01:46

标签: java android sqlite

我尝试从准备好的SQLite数据库中获取数据并将其写入TextView但我收到此错误。

这是我的DataBaseHelperClass.java:

package com.ehliyet;

import java.io.File;
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;

public class DataBaseHelperClass extends SQLiteOpenHelper{
 //The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.ehliyet/assets/";
// Data Base Name.
private static final String DATABASE_NAME = "test.db";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "questions";

public Context context;
static SQLiteDatabase sqliteDataBase;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 * Parameters of super() are    1. Context
 *                              2. Data Base Name.
 *                              3. Cursor Factory.
 *                              4. Data Base Version.
 */
public DataBaseHelperClass(Context context) {       
    super(context, DATABASE_NAME, null ,DATABASE_VERSION);
    this.context = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * 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.
 * */
public void createDataBase() throws IOException{
    //check if the database exists
    boolean databaseExist = checkDataBase();

    if(databaseExist){
        // Do Nothing.
    }else{
        this.getWritableDatabase();         
        copyDataBase(); 
    }// end if else dbExist
} // end createDataBase().

/**
 * 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
 */
public boolean checkDataBase(){
    File databaseFile = new File(DB_PATH + DATABASE_NAME);
    return databaseFile.exists();        
}

/**
 * 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 transferring byte stream.
 * */
private void copyDataBase() throws IOException{ 
    //Open your local db as the input stream
    InputStream myInput = context.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 input file to the output file
    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(); 
}

/**
 * This method opens the data base connection.
 * First it create the path up till data base of the device.
 * Then create connection with data base.
 */
public void openDataBase() throws SQLException{      
    //Open the database
    String myPath = DB_PATH + DATABASE_NAME;
    sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
}

/**
 * This Method is used to close the data base connection.
 */
@Override
public synchronized void close() { 
    if(sqliteDataBase != null)
        sqliteDataBase.close(); 
    super.close(); 
}

/**
* Apply your methods and class to fetch data using raw or queries on data base using 
* following demo example code as:
*/
public String getDataDB(){
    String query = "select QLect From questions";
    Cursor cursor = sqliteDataBase.rawQuery(query, null);
    String userName = null;
    if(cursor.getCount()>0){
        if(cursor.moveToFirst()){
    do{
                userName = cursor.getString(0);
            }while (cursor.moveToNext());
        }
    }
    return userName;
}


@Override
public void onCreate(SQLiteDatabase db) {
    // No need to write the create table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // No need to write the update table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
    // We should not update it as requirements of application.
}   
}

MainActivity.Java:

package com.ehliyet;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        Button btBasla = (Button)findViewById(R.id.button1);
        btBasla.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                DataBaseHelperClass myDBHelper = new DataBaseHelperClass(MainActivity.this);
                myDBHelper.openDataBase();
                String textdt = myDBHelper.getDataDB();
                myDBHelper.close();
                TextView txtSoru = (TextView)findViewById(R.id.textView1);
                txtSoru.setText(textdt);
            }
        });
    }
}

单击按钮时,这是LogCat:

    08-09 18:46:38.128: E/SQLiteLog(1172): (14) cannot open file at line 30174 of [00bb9c9ce4]
    08-09 18:46:38.128: E/SQLiteLog(1172): (14) os_unix.c:30174: (2) open(/data/data/com.ehliyet/assets/test.db) - 
    08-09 18:46:38.178: E/SQLiteDatabase(1172): Failed to open database '/data/data/com.ehliyet/assets/test.db'.
    08-09 18:46:38.178: E/SQLiteDatabase(1172): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at com.ehliyet.DataBaseHelperClass.openDataBase(DataBaseHelperClass.java:101)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at com.ehliyet.MainActivity$1.onClick(MainActivity.java:23)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.view.View.performClick(View.java:4084)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.view.View$PerformClick.run(View.java:16966)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.os.Handler.handleCallback(Handler.java:615)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.os.Handler.dispatchMessage(Handler.java:92)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.os.Looper.loop(Looper.java:137)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at android.app.ActivityThread.main(ActivityThread.java:4745)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at java.lang.reflect.Method.invokeNative(Native Method)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at java.lang.reflect.Method.invoke(Method.java:511)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    08-09 18:46:38.178: E/SQLiteDatabase(1172):     at dalvik.system.NativeStart.main(Native Method)
    08-09 18:46:38.178: D/AndroidRuntime(1172): Shutting down VM
    08-09 18:46:38.188: W/dalvikvm(1172): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
    08-09 18:46:38.258: E/AndroidRuntime(1172): FATAL EXCEPTION: main
    08-09 18:46:38.258: E/AndroidRuntime(1172): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at com.ehliyet.DataBaseHelperClass.openDataBase(DataBaseHelperClass.java:101)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at com.ehliyet.MainActivity$1.onClick(MainActivity.java:23)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.view.View.performClick(View.java:4084)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.view.View$PerformClick.run(View.java:16966)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.os.Handler.handleCallback(Handler.java:615)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.os.Handler.dispatchMessage(Handler.java:92)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.os.Looper.loop(Looper.java:137)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at android.app.ActivityThread.main(ActivityThread.java:4745)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at java.lang.reflect.Method.invokeNative(Native Method)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at java.lang.reflect.Method.invoke(Method.java:511)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    08-09 18:46:38.258: E/AndroidRuntime(1172):     at dalvik.system.NativeStart.main(Native Method)
    08-09 18:46:40.008: I/Process(1172): Sending signal. PID: 1172 SIG: 9

1 个答案:

答案 0 :(得分:3)

任何Android设备上都没有名为/data/data/com.ehliyet/assets/test.db的文件,包括您的任何设备。 assets/目录位于开发计算机上,而不是Android中。

use SQLiteAssetHelper了解一个经过测试的解决方案,用于在您的应用程序中打包数据库。