首先,请勿将此问题标记为重复。我搜索了所有可能的选项并尝试了它们但它仍然无效。更改了数据库版本,清除了数据并重新安装了应用程序。我将数据库正确放置在数据库文件夹中。编译错误时仍然没有找到这样的表。帮我弄清楚我在这段代码中缺少什么,或者我做错了什么。
public class DatabaseHelper extends SQLiteOpenHelper {
String DB_PATH = null;
private static String DB_NAME = "externaldatabase";
private SQLiteDatabase myDataBase;
private final Context myContext;
Cursor c =null;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 11);
this.myContext = context;
this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
Log.e("Path 1", DB_PATH);
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
e.toString();
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@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) {
if (newVersion > oldVersion)
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
return myDataBase.query("rates_table", null, null, null, null, null, null);
}
public String getFare(String name, String depart){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"rate"};
c = db.rawQuery("select rate from rates_table where place1 = '"+name+"'and place3 = '"+depart+"' or place1 = '"+depart+"'and place3 = '"+name+"'", new String[]{});
StringBuffer buffer = new StringBuffer();
while(c.moveToNext()){
String employyename = c.getString(0);
buffer.append(employyename+"");
}
return buffer.toString();
} }
答案 0 :(得分:0)
您在onCreate()
方法中没有任何代码。在createDatabase()
内调用onCreate()
方法。
@Override
public void onCreate(SQLiteDatabase db) {
createDataBase();
}
答案 1 :(得分:0)
你没有在onCreate()中为表创建编写任何代码。请注意SQLiteOpenHelper类: -
onCreate() - 这是我们需要编写create table的地方 声明。在创建数据库时调用此方法。
onUpgrade() - 在升级数据库时调用此方法 修改表结构,向数据库添加约束等,
所以在onCreate()中你必须为create table编写逻辑。