我想復制一個自定義的 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();