简体   繁体   中英

How to store multiple DATES in sqlite android and fetch them to display in a List?

I have an android activity with a list of dates. Date are date_from and date_to. so User might enter many dates (date_from and date_to) for some events that occurred in past. I want to store these dates in sqlite database so I made a table of user and entered all date_from in one column and date_to in another column.

when user exit the activity obviously android kills that activity so its empty. Now i want to fetch all those dates back and store them back into the list view so that user can see that these are the dates that are already entered. May be my approach is wrong, if anybody can just guide me a better approach to achieve this functionality.

Thank you.这是我的桌子图片

To retrieve data you can use cursors , get the data into an array and display it in a list view using adapters.

String selectQuery = "SELECT  * FROM my_table";
SQLiteDatabase db = this.getReadableDatabase();
String [] values = [];
int i = 0;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
    do {
         int keyRowIdColumnIndex = cursor.getColumnIndex("toDate");
         String yourValue = cursor.getString(keyRowIdColumnIndex);
         values[i++] = yourValue;
    } while (cursor.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
          android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter); 

You can store it in string in database and then can retrieve from database and change back to date using following methods:

Change Date to String

public String dateToddMMyyyyString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",
                Locale.getDefault());
        return sdf.format(date);
    }

Change String to Date:

public Date ddMMyyyyStringToDate(String ddMMyyyy) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",
                Locale.getDefault());

        return sdf.parse(ddMMyyyy);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM