Nube1 Nu2 Nube1 Nu2 - 2 months ago 9
Android Question

Android sqlite store data from List<LocalDate>

I'm trying to store each data as each rows on the database. I managed to store the data but it is being stored as one row for all the data. Btw, I'm using

import org.joda.time.LocalDate


Result I'm getting is:

|tbl_id | days
--------------------------------------------------------------------------------------------------------------------------------
|1 | 2016-9-10, 2016-9-11, 2016-9-12 2016-9-13, 2016-9-14, 2016-9-15, 2016-9-16, 2016-9-17, 2016-9-18, 2016-9-19, 2016-9-20


What im after is

|tbl_id | days
-------------------
|1 | 2016-9-10
|2 | 2016-9-11
|3 | 2016-9-12


Here's what i have so far

method days

String from = "2016-9-10";
String to = "2016-9-20";

SimpleDateFormat df = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

try {

String reformatDateFrom = myFormat.format(df.parse(from));
String reformatDateTo = myFormat.format(df.parse(to));
LocalDate start = LocalDate.parse(reformatDateFrom);
LocalDate end = LocalDate.parse(reformatDateTo);
List<LocalDate> days= new ArrayList<>();

while (!start.isAfter(end)) {
days.add(start);
start = start.plusDays(1);

}

Toast.makeText(this, "This" + days,
Toast.LENGTH_LONG).show();
databaseHandler.insertDays(String.valueOf(days));
} catch (ParseException pe) {
pe.printStackTrace();
}


method insert

public void insertDays(List<String> days) {
int size = days.size();

sqLiteDatabase = this.getWritableDatabase();
try {
for(int i = 0; i < size; i++) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DAYS, days.get(i));
sqLiteDatabase.insert(TABLE_DAYS, null, contentValues);
}
sqLiteDatabase.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteDatabase.close();
}

}

Answer

Change

databaseHandler.insertDays(String.valueOf(days));

to

databaseHandler.insertDays(days);

The first version converts your list to a String representation and calls a different insertDays() method than the one you have shown here.

Comments