I'm trying to retrieve data from CSV to SQLite DB, all the Strings are properly saved. But Integers and Doubles are not, all of them saves as null. But how to split Integers and Doubles and put them in ContentValues? Here I'm trying to make this with ContentValues:
public static void importSomeDBfromCSV(){
try{
FileReader file = new FileReader(currentFilePathOfsavingCSVtoSD);
BufferedReader buffer = new BufferedReader(file);
String line = "";
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.beginTransaction();
try {
while ((line = buffer.readLine()) != null) {
String[] colums = line.split(",");
if (colums.length != 8) {
Log.d("CSVParser", "Skipping Bad CSV Row");
continue;
}
ContentValues cv = new ContentValues(8);
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME, colums[0].trim());
// needs to be saved as Double
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE, colums[1].trim());
// needs to be saved as Integer
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY, colums[2].trim());
// needs to be saved as Integer
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SOLD, colums[3].trim());
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_BARCODE, colums[4].trim());
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_LOCATION, colums[5].trim());
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_CATEGORY, colums[6].trim());
cv.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NOTE, colums[7].trim());
db.insert(TABLE_NAME, null, cv);
}
} catch (IOException e) {
e.printStackTrace();
}
db.setTransactionSuccessful();
db.endTransaction();
successImportingFromCSV=true;
Log.v(LOG_TAG, "Restore is successful");
}catch(Exception e){
e.printStackTrace();
successImportingFromCSV=false;
Log.e(LOG_TAG, "Failed to restore from csv " + e);
}
}
I don't believe that there is anything wrong with the code that you have supplied, rather that the data itself may be lacking or alternately the subsequent data retrieval is incorrect. I suspect that the latter (see additional lines added that appears to rule out anything wrong with the input data).
Take this file (in downloads/product.csv) :-
and a slightly modified
importSomeDBfromCSVmethod :-Then making use of some generic database/cursor routines from Are there any methods that assist with resolving common SQLite issues? the following is run :-
Output/Conclusion
Part 1 - Output from
importSomeDBfromCSVmethod.Part 2 - Output from
logDatabaseInfoPart 3 - Output from
logCursorDatamethodAdding a line, resulted in Bad Row Skipped, as follows :-
Adding a line, resulted in Bad Row Skipped, as follows :-