我有一个工作正常的数据库。现在我要将我的数据库文件添加到项目中。我在资产文件夹中有一个数据库文件。但是不知道如何在项目的任何主体中导入它来解决我的问题。
这是我的dbhelper类
public class FoodDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "pkfood_calories.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ Food.NewDishInfo.TABLE_NAME+"("
+ Food.NewDishInfo.DISH_NAME+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_QUANTITY+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_CALORIE+" INTEGER,"
+ Food.NewDishInfo.DISH_FAT+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_PROTEIN+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_SUGAR+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_VITAMINS+" TEXT NOT NULL);";
public FoodDbHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATION","Database created / opened...");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATION","Table created...");
}
public void addInformations(String name ,String quantity, Integer calorie, String fat ,
String protein,String sugar,String vitamins, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
contentValues.put(Food.NewDishInfo.DISH_NAME,name);
contentValues.put(Food.NewDishInfo.DISH_QUANTITY,quantity);
contentValues.put(Food.NewDishInfo.DISH_CALORIE,calorie);
contentValues.put(Food.NewDishInfo.DISH_FAT,fat);
contentValues.put(Food.NewDishInfo.DISH_PROTEIN,protein);
contentValues.put(Food.NewDishInfo.DISH_SUGAR,sugar);
contentValues.put(Food.NewDishInfo.DISH_VITAMINS,vitamins);
db.insert(Food.NewDishInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATION","one row inserted...");
}
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null,"DISH_NAME ASC");
return cursor;
}
答案 0 :(得分:1)
假设您的数据库文件名为" a.db",您可以这样做:
try {
File file = new File(dbfile); //dbfile is a file path that you save the database
if (!file.exists()) {
Log.e("cc", "file");
InputStream is = Context.getAssets().open("school.db");
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
fos.flush();
}
fos.close();
is.close();
}
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
} catch (FileNotFoundException e) {
Log.e("cc", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("cc", "IO exception");
e.printStackTrace();
} catch (Exception e) {
Log.e("cc", "exception " + e.toString());
}