复制自定义的 sqlite 数据库到 android 中的错误

我想复制一个自定义的 sqlite 数据库到 android 中

public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
private static String DB_PATH = "/data/data/mypackagename/databases/";//path of our database
private static String DB_NAME ="application-database";// Database name
private SQLiteDatabase mDataBase; 
private final Context mContext;
public DataBaseHelper(Context context) 
{
    super(context, DB_NAME, null, 1);
    DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    this.mContext = context;
}   
public void createDataBase() throws IOException
{
    //If database not exists copy it from the assets
      boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist)
    {
        this.getReadableDatabase();
        this.close();
        try 
        {
            //Copy the database from assests
            copyDataBase();
            Log.e(TAG, "createDatabase database created");
        } 
        catch (IOException mIOException) 
        {
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

当运行到 InputStream mInput = mContext.getAssets().open(DB_NAME);
给出一个错误,程序直接跳转到

catch (IOException mIOException) 
        {
            throw new Error("ErrorCopyingDataBase");
        }

数据库是在 assets 文件夹中。
这个问题出在哪里呢?

   /**
     * 
     * @param sqlQuery SQL query to be fired
     * @param myObj Object to be fetched
     * @return Returns a Vector object containing raws fetched by the sqlQuery
     */

    public ArrayList<Object> fetchAllRows(String sqlQuery, Object myObj)
    {
        ArrayList<Object> records = new ArrayList<Object>();
        Object newObj;
        Cursor cursor = execQuery(sqlQuery);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                //          System.out.println("Test While");
                newObj = ClassUtils.newObject(myObj);
                for (int i = 0; i < cursor.getColumnCount(); i++) {
                    String key = cursor.getColumnName(i);
                    String value = cursor.getString(i);
                    if (value == null) {
                        value = "";
                    }
                    ClassUtils.objectMapping(newObj, key, value);
                }
                records.add(newObj);
            }
            cursor.close();
        }
        return records;
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {

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

    }
}

在第一个 activity 中添加下面的代码:

 Global.context = this;
 Global.dbMain = new DBConnect(this, Global.DB_MAIN);

创建一个 Global.java 文件

public class Global 
{
    public static String DB_PATH = "data/data/YOUR_PACKAGE_NAME/databases/";
    public static final String DB_MAIN = "Database.sqlite";

    public static Context context;
    public static DBConnect dbMain;
}

现在假定你想从表格中选择信息

Global.dbMain.openDataBase();
System.out.println("database open ");
    try
    {
      Cursor c = Global.dbMain.execQuery("select * from tableName", null);
      while(c.moveToNext())
       {
         System.out.println("in while");
         String str= c.getString(1);
       }
      c.close();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
Global.dbMain.close();

你需要先把数据库解压到SD卡上,然后去读取SD卡上的db文件。

public class ImportDBFile {

private final String TAG = ImportDBFile.class.getSimpleName() ; 
private final int BUFFER_SIZE = 40*1024;
public String DB_NAME = "xxx.db"; // save db file name
public String PACKAGE_NAME = null;
public String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() ;

public final String Package_path = Environment.getExternalStorageState() ;

private Context context;


public ImportDBFile(){}

public ImportDBFile(Context context, String dbName) {
    this.context = context;
    DB_NAME = dbName ; 
}

public void openDatabase() {
    ApplicationInfo applicationInfo = context.getApplicationInfo() ;
    PACKAGE_NAME = applicationInfo.packageName ;
    copyDataBaseToAPP(DB_PATH +"/"+ PACKAGE_NAME +"/databases/" + DB_NAME);
}

private void copyDataBaseToAPP(String dbfile) {
    InputStream is = null;
    FileOutputStream fos  = null ;

    try {
        // if the db file does not exist, first import the db file
        if (!(new File(dbfile).exists())) {
            File file = new File(dbfile.substring(0, dbfile.lastIndexOf("/"))) ;
            file.mkdirs();
            System.out.println("Create database directory successed!");
            file.createNewFile() ;
            AssetManager am =  null ;    
            am = this.context.getAssets();    
            is = am.open(DB_NAME);    // to import the db file
            fos = new FileOutputStream(dbfile);
            byte[] buffer = new byte[BUFFER_SIZE];
            int count = 0;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
            }

            Log.i(TAG, "import " + DB_NAME + "successful!") ;
        }
    } catch (FileNotFoundException e) {
        Log.e("Database", "File not found");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Database", "IO exception");
        e.printStackTrace();
    }finally{
        try {
            fos.close();
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public void exportDBToSDCard(){
    ApplicationInfo applicationInfo = context.getApplicationInfo() ;
    PACKAGE_NAME = applicationInfo.packageName ;
    String path = DB_PATH +"/"+ PACKAGE_NAME +"/databases/" + DB_NAME ;

    FileInputStream fis = null ;
    FileOutputStream fos = null ;
    try {
        fis = new FileInputStream(new File(path)) ;
        System.out.println(SDCardUtil.getSDCardPath()+"/"+DB_NAME);
        System.out.println(Environment.getExternalStorageDirectory()
                .getAbsolutePath()); ;
        fos = new FileOutputStream(SDCardUtil.getSDCardPath()+"/"+DB_NAME) ;
        byte[] buffer = new byte[BUFFER_SIZE];
        int count = 0;
        while ((count = fis.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
        }
        fos.close();
        fis.close();
        System.out.println("import to sdcard success!");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            fos.close();
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}

}