0

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!

Izzati
  • 35
  • 7
  • If you want to pack the csv file with your app then put it in assets folder at design time. – blackapps Apr 15 '20 at 11:08
  • @blackapps okay then, how about the code? Should I called the function of saveFood() on the other page or there have any other ways to copy the data from csv to sqlite db in android? – Izzati Apr 15 '20 at 11:39
  • Open an input stream for the csv file in assets. Then use the readers on the stream as you do now. – blackapps Apr 15 '20 at 11:59
  • @blackapps I tried to use InputStreamReader is = new InputStreamReader(getAssets() .open("filename.csv")); but, it say that getAsset() method cannot be resolve. – Izzati Apr 15 '20 at 13:00
  • Your code is not in an activity? – blackapps Apr 15 '20 at 15:47
  • @blackapps actually I put it in the DatabaseHelper's class since all the declaration of the database and table I put it in there. So I thought that it would be easier because I don't need to declare/create the syntax for creating table/DB twice in my activity. Then what if I put it on my activity, so do I need to declare the DB and table? because from the coding above, I used db.transaction() and I declare db as SQLiteDatabase db – Izzati Apr 15 '20 at 16:46
  • `public void saveFood()` make it `public void saveFood(Context context)` then you can use context.getAsset(). – blackapps Apr 15 '20 at 16:49
  • @blackapps I already move the code from DatabaseHelper's class to the activity class. And I already edit and updated some codes in the question above. But, I still cannot read the file. It shows an error on the AssetManager – Izzati Apr 15 '20 at 18:10
  • Who shows an error? And which error exactly? – blackapps Apr 16 '20 at 07:03
  • `AssetManager manager = context.getAssets()` That should be `AssetManager manager = getAssets()` if your code is in an activity class. – blackapps Apr 16 '20 at 07:06
  • `catch (IOException e) { e.printStackTrace(); }` Even if there is a catch you continue as if all was ok. You should return there. And before that use a toast to inform the user. – blackapps Apr 16 '20 at 07:08
  • @blackapps there shown no error anymore in the coding. But, I when checked the DB file right after the application successfully run, however, the table in the DB turns out to be still empty. I don't whether there is a problem with the code or what. Do you know why? – Izzati Apr 16 '20 at 15:40
  • You catch several times an exception. Which is good. But.. after such a catch you continue as if everything went ok. No good. You should first display a toast telling the user what went wrong. And then return. Dont continue then. – blackapps Apr 16 '20 at 15:53
  • @blackapps I already display a toast in the catch. But it seems like the process does not enter the catch. I have updated the code on the question above. But not sure if what I do is correct or not. – Izzati Apr 16 '20 at 16:47
  • You should put a `return;` in your first catch as now you blindly continue with your code. And display `e.getMessage()` in the toast so the user is informed. – blackapps Apr 16 '20 at 17:13
  • @blackapps it's worked! thank you for helping! But, do you know how to check if the record already exists or not in the DB, so that the data won't be duplicated? Or if possible can you show me how? I would really appreciate it. – Izzati Apr 18 '20 at 10:10

0 Answers0