我想复制一个自定义的 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();
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。