我想制作书籍并使用这些代码:
public class Main extends Activity {
private database db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new database(this);
db.useable();
}
}
和数据库类:
public class database extends SQLiteOpenHelper {
public final String path = "data/data/com.example.book/databases/";
public final String Name = "database";
public SQLiteDatabase mydb;
private final Context mycontext;
public database(Context context) {
super(context, "database", null, 1);
mycontext = context;
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void useable() {
boolean checkdb = checkdb();
if (checkdb) {
} else {
this.getReadableDatabase();
try {
copydatabase();
}
catch (IOException e) {}
}
}
public void open() {
mydb = SQLiteDatabase.openDatabase(path + Name, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public void close() {
mydb.close();
}
public boolean checkdb() {
SQLiteDatabase db = null;
try {
db = SQLiteDatabase.openDatabase(path + Name, null,
SQLiteDatabase.OPEN_READONLY);
}
catch (SQLException e) {
}
mydb.close();
return db != null ? true : false;
}
public void copydatabase() throws IOException {
OutputStream myOutput = new FileOutputStream(path + Name);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = mycontext.getAssets().open(Name);
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
但我强行关闭了这些错误
E/SQLiteDatabase(1567): Failed to open database 'data/data/com.example.book/databases/database'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
我的数据库文件位于assets文件夹中,带有"数据库"名字,我的模拟器是genymotion
答案 0 :(得分:0)
试试这个: 取代
public final String path = "data/data/com.example.book/databases/";
与
String yourPath = myContext.getFilesDir().getAbsolutePath().replace("files",
"databases")+File.separator + DB_NAME;