我正在开发一个 android 应用程序,我将我的 sqlite 数据库导入到 android 项目中.. 数据库在模拟器上运行良好,但是当我在我的设备上尝试该应用程序时它不起作用并输出一条消息:不幸的是,appname 有停了下来。
我将数据库放在项目的 assets 文件夹中,然后使用此代码复制它:
try {
String destPath = "/data/data/" + getPackageName() + "/databases/MyDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
复制数据库功能:
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
DBAdapter 类:
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "username";
public static final String KEY_PASSWORD = "password";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "users";
private static final int DATABASE_VERSION = 4;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---retrieves all the users---
public Cursor getAllusers()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_PASSWORD}, null, null, null, null, null);
}
//---retrieves a particular user---
public User getuser(String username) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_PASSWORD}, KEY_NAME + "=" + "'"+username+ "'", null,
null, null, null, null);
if(mCursor.moveToFirst())
{
mCursor.moveToFirst();
User u=new User(Integer.valueOf(mCursor.getString(0)),mCursor.getString(1),mCursor.getString(2));
return u;
}else
return null;
}
}
非常感谢你提前