为什么我收到错误“无法打开数据库”在Android?
问题描述:
我搜索了我的问题,但没有解决方案有效!!
我有这样的课程:
I have searched allot for my problems but none of the solutions work!!
I have a class like this:
public class database extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.MEN/databases/";
private static String DB_NAME = "men";
private SQLiteDatabase myDataBase;
private final Context myContext;
public database(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public String openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor c=myDataBase.rawQuery("select Mistake from info",null);
String s=c.getString(0);
return s;
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
我在另一个类中使用它代码如下:
and i use it in another class by code like this:
database db;
db = new database(this);
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
String t;
t=db.openDataBase();
TextView tv= (TextView) findViewById(R.id.textView);
tv.setText(t);
}catch(SQLException sqle){
try {
throw sqle;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
但我每次都会收到错误我跑了!!!!
任何人都可以帮助我?
but i get that error every time i run it!!!!
anybody can help me??
答