所以我想在我的Android应用程序中使用自己的SQLite数据库。但是当我试图获取一些数据时,我没有得到这样的表异常。我已经尝试重新安装App。
这是 DatabaseHelper 代码:
package pl.edu.ur.kulturalia;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String databasePath = "/data/data/pl.edu.ur.kulturalia/databases/";
public static String databaseName = "kulturalia";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, databaseName, null, 1);
this.myContext = context;
System.out.println(myContext);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
e.getMessage();
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = databasePath + databaseName +".db";
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private void copyDataBase() throws IOException {
String outFileName = databasePath + databaseName+".db";
System.out.println(outFileName);
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int i, r;
AssetManager am = myContext.getAssets();
String fn = String.format(databaseName);
InputStream is = am.open(databaseName);
while ((r = is.read(buffer)) != -1)
myOutput.write(buffer, 0, r);
is.close();
myOutput.flush();
myOutput.close();
System.out.println(myOutput);
}
public void openDataBase() throws SQLException {
String myPath = databasePath + databaseName+".db";
System.out.println(myPath);
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
System.out.println(myDataBase);
}
public String getKoncert(int id, String tableName) {
String sql = "Select nazwa from " + tableName + " where _id=?";
System.out.println(sql);
System.out.println(myDataBase);
Cursor cursor = myDataBase.rawQuery(sql, new String[]{String.valueOf(id)});
if (cursor != null) {
cursor.moveToFirst();
String name = cursor.getString(1);
cursor.close();
return name;
}
cursor.close();
return "cos";
}
}
这是我正在使用这个帮助器的代码:
try {
db.createDataBase();
db.openDataBase();
db.getKoncert(1,"Czwartek");
} catch (IOException e) {
e.printStackTrace();
}