无法将我的数据库文件存入应用程序

时间:2012-03-28 09:53:49

标签: android database

我创建了应用程序,我只需要访问数据表单资源文件夹。我正在使用数据库帮助程序类来打开数据库,但我无法访问数据库,我正在使用我的代码

public class DidUMean extends Activity {
DataBaseHelper myDbHelper;
public SQLiteDatabase mydatabase;
String searchWord;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.didumean);

    myDbHelper = new DataBaseHelper(DidUMean.this);

    didYouMean(searchWord);

}

public void didYouMean(String searchWord) {
    myDbHelper.openDataBase();
    mydatabase = myDbHelper.getWritableDatabase();
    Cursor cc = mydatabase.rawQuery("SELECT COUNT(*) FROM tblVocab",
            null);
    try {
        if (cc.getCount() == 0) {
            System.out.println("----> "+cc.getCount());
        }
    } catch (SQLException sqle) {
        System.out.println(sqle);
        throw sqle;
    } finally {
        myDbHelper.close();
    }
}
}

我在Logcat中遇到以下错误。

03-28 15:12:48.945: ERROR/AndroidRuntime(1995): FATAL EXCEPTION: main
03-28 15:12:48.945: ERROR/AndroidRuntime(1995): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lauruss.verb2verbe/com.lauruss.verb2verbe.DidUMean}: android.database.sqlite.SQLiteException: unable to open database file
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.os.Looper.loop(Looper.java:123)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at java.lang.reflect.Method.invokeNative(Native Method)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at java.lang.reflect.Method.invoke(Method.java:521)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at dalvik.system.NativeStart.main(Native Method)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995): Caused by: android.database.sqlite.SQLiteException: unable to open database file
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1812)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:817)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at com.lauruss.verb2verbe.DataBaseHelper.openDataBase(DataBaseHelper.java:109)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at com.lauruss.verb2verbe.DidUMean.didYouMean(DidUMean.java:27)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at com.lauruss.verb2verbe.DidUMean.onCreate(DidUMean.java:22)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-28 15:12:48.945: ERROR/AndroidRuntime(1995):     ... 11 more

2 个答案:

答案 0 :(得分:1)

public class DataBaseHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.lauruss.verb2verbe/databases/";
private static String DB_NAME = "v2v.db";
private SQLiteDatabase myDataBase; 
private final Context myContext;

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

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

/ **      *在系统上创建一个空数据库,并使用您自己的数据库重写它。      * * /     public void createDataBase()抛出IOException {

    boolean dbExist = checkDataBase();

    if(dbExist){
        Log.d("Rikta", "Database Exist");
        //do nothing - database already exist

        }else{
            Log.d("Rikta", "Database Does Not Exist");
            this.getReadableDatabase();
        try {
            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;
        Log.d("Maulik", myPath);
    //  checkDB = SQLiteDatabase.openOrCreateDatabase(myPath, null);
        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;
    Log.d("copyDataBase", outFileName);
    //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;
    Log.d("openDatabase", myPath);
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
 }

@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) {
}

    // 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.

}

答案 1 :(得分:0)

如果你想查看你的数据库,那么它会出现在...中 文件资源管理器 - 数据\数据\您的包名称\ database \ Database Name.db

为数据库创建你的课程......

public class MySQLiteHelper extends SQLiteOpenHelper

然后写下面的方法...

public MySQLiteHelper open() throws SQLException 
{
    db = this.getWritableDatabase();
    return this;
}

public MySQLiteHelper(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}


@Override
public void onCreate(SQLiteDatabase database) 
{

    database.execSQL(DATABASE_CREATE);
    }

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version "
            + oldVersion + " to " + newVersion
            + ", which will destroy all old data");
    database.execSQL("DROP TABLE IF EXISTS " + TABLE_SUBJECT);
            }

然后,您需要在activity.java

中创建此databasehelper类的对象
public class AddQuestionActivity extends Activity
db=new MySQLiteHelper(getBaseContext());
                    db.getWritableDatabase();

Click here