I'm new on developing an application using Android Studio. Currently, I want to store all my data from CSV file into SQLiteDatabase through android. So, what I expected is to copy all the data from .csv file to the database by default (if the data do not exist in the DB yet). What I mean by default is, I want to copy the data without importing the file first. So then when the application installed, it will automatically copy the data from the .csv file to the SQLiteDatabase in android.
I have tried some code here:
SQLiteOpenHelper helper;
SQLiteDatabase db;
helper = new DatabaseHelper(this);
db = helper.getWritableDatabase();
String mCSVfile = "food.csv";
AssetManager manager = getAssets();
InputStream inStream = null;
try {
inStream = manager.open(mCSVfile);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error 1", Toast.LENGTH_SHORT).show();
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line = "";
String tableName = DatabaseHelper.FOOD;
String columns = "food_name, food_category, food_serving, food_serving_size, food_calorie, food_carbs, food_protein, food_fat";
String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
String str2 = ")";
String str3 = ";";
db.beginTransaction();
while (true) {
try {
if (!((line = buffer.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error 2", Toast.LENGTH_SHORT).show();
break;
}
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
sb.append("'" + str[0] + "',");
sb.append("'" + str[1] + "',");
sb.append("'" + str[2] + "',");
sb.append(str[3] + ",");
sb.append(str[4] + ",");
sb.append(str[5] + ",");
sb.append(str[6] + ",");
sb.append(str[7] + "");
sb.append(str2);
db.execSQL(sb.toString());
sb.append(str3);
}
db.setTransactionSuccessful();
db.endTransaction();
I put this code in the onCreate on the main activity. And already put the CSV file in the Assets folder. However, it seems like there is error on the AssetManager.
Can anyone help me with this? I have tried to refer tutorial here and there but it seems that I can't found any solution yet. Thank you in advance!