的问题是getReadableDatabase()方法不返回你想要的数据库。您需要在应用程序内部构建它,或者将其与应用程序捆绑在一起(使用Assets)。以下是代码片段做两件事:
建库
static final string DATABASE_CREATE = "create table if not exists " + "product " + "(" +
TABLE_COLUMN_1 + " " + COLUMN_1_TYPE + ", " +
TABLE_COLUMN_2 + " " + COLUMN_2_TYPE + ", "; //and so on
public class MySQLHelper extends SQLiteOpenHelper {
MySQLHelper(Context context) {
super(context, YOUR_DATABASE_NAME, null, YOUR_DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
}
catch(SQLException e) {
e.printStackTrace();
}
}
以资产复制预建数据库
首先,你需要把你的SQL文件在您的应用程序的资产文件夹中。然后把这个代码的主要活动的onCreate()方法中:
File f = new File(this.getDatabasePath().getAbsolutePath() + "/mydatabase.db";
if(!f.exists()) {
if(f.getParentFile().exists() || f.getParentFile().mkdirs()) {
f.createNewFile();
InputStream inputStream = getBaseContext().getAssets().open("mydatabase.db");
OutputStream outputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length;
while((length = dbStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.flush();
outputStraem.close();
}
else
throw new IOException("Database input error");
}
}
这是使用假设预建数据库被放置在“mydatabase.db”文件。
你需要显示你的数据库类的'onCreate()'代码 – Shubhank
只需简单地写''cur = db.rawQuery(“SELECT * FROM product”);''因为你没有指定任何特定的列。 – GrIsHu
你有onCreate在你的productDB类里面? – Shubhank