Solution 1 :
It would be nice to look on the following articles. Article1 and article2 focuses on using room to import csv using room.
If you can use a different library, this is also helpful.
I will advise to break this functionality into two tasks.
- Extract data from CSV/Excel file
- Put that data into the database
1 To extract data from CSV/Excel File, you can use the following code.
CSVReader csvReader = new CSVReader(new FileReader(Environment.getExternalStorageDirectory() + "/" + TableName));
String[] nextLine;
int count = 0;
StringBuilder columns = new StringBuilder();
StringBuilder value = new StringBuilder();
while ((nextLine = csvReader.readNext()) != null) {
// nextLine[] is an array of values from the line
for (int i = 0; i < nextLine.length - 1; i++) {
if (count == 0) {
if (i == nextLine.length - 2)
columns.append(nextLine[i]);
else
columns.append(nextLine[i]).append(",");
} else {
if (i == nextLine.length - 2)
value.append("'").append(nextLine[i]).append("'");
else
value.append("'").append(nextLine[i]).append("',");
}
}
- To put the extracted data into the database you can use the following code.
Create a raw query function in your DAO.
@RawQuery
Boolean insertDataRawFormat(SupportSQLiteQuery query);
Using that query put the data into the Database
SimpleSQLiteQuery query = new SimpleSQLiteQuery("Insert INTO " + tableName + " (" + columns + ") " + "values(" + value + ")",
new Object[]{});
getDb().cashDrawerDao().insertDataRawFormat(query);
Problem :
I want to import an excel file into my database designed with room library on android.
I can export the database using a library but for import i need to check items and handle conflicts but I don’t know how.
Comments
Comment posted by Community
Please provide enough code so others can better understand or reproduce the problem.