Order list of dates in String format - android

I've got a list which contains x records with dates. The thing is all my dates are in the String format and come as strings from the database.
I would really like to order my List by date (in String format) but I really have no clue how to do this.
Without further ado, this is my list, which is a custom list.
List<Finance> finances;
The list contains following fields:
public class Finance {
private int id;
private int categoryId;
private int limitId;
private double amount;
private String date;
private String description;
}
And this is the dateformat I have (in String):
16/10/2013
15/12/2013
15/11/2013
14/9/2013
How would I be able to sort this custom list by date? I've seen many examples with Collections.sort but I cannot use that because of my custom list type.
I've also seen some examples with Comparable but I didn't really understand those..
Could anybody tell me what would be the best way to achieve a chronical order by date of mist list please?
I would also like the most lightweighted method, to use as little resources as I can.
EDIT: I still didn't find a working solution (19/12) and still hope for a response here..
Thank you
Yenthe

Okay since there where no good answers and barely any responses I decided to dig into it until I fixed it.
The 'easiest' way to come around this is to insert all your dates into the database as yyyy-mm-dd format. For a great explenation on that part you should look here: https://stackoverflow.com/a/5733535/2262409
When you place the date in yyyy-mm-dd and just do a order by Date in your SQLite the dates will be ordered correct. When you place them in dd-mm-yyyy they will not be ordered correct.
Long answer short:
Solved it in the SQL part. I insert records in the format yyyy-mm-dd I get them by
String selectQuery = "SELECT * FROM Finance ORDER BY date desc";
And then I reformat them to dd-mm-yyyy right before the user sees it. Example:
String date = String.valueOf(values.get(position).getDate());
// we will format yyyy-mm-dd to dd-mm-yyyy for readability.
//the sql has ordered our dates correctly already.
String firstPartDate = date.substring(8, 10);
String secondPartDate = "/" + date.substring(5,7);
String thirdPartDate = "/" + date.substring(0,4);
String fullCorrectDate = firstPartDate + secondPartDate + thirdPartDate;
Log.i("firstpart", firstPartDate + secondPartDate + thirdPartDate);
dateFinance.setText(fullCorrectDate);

Related

Sort arraylist to display items by date

i am developing a news app which it composed of:
Title,description,time,date
The date format is as : 12/7/2017
When i am adding multiples news they are showed randomly on the recyclerview.
What is the best way to use Comparator object to sort the arraylist by date so when i add a news it must show up in recyclerview top.
This is my working code :
JSONArray array = new JSONArray(response);
JSONObject jsonObject = null;
post_array2.clear();
Simplenews_data p;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
int id_simplenews = jsonObject.getInt("id_simplenews");
String name_simplenews = jsonObject.getString("name_simplenews");
String image_simplenews = jsonObject.getString("image_simplenews");
String desc_simplenews = jsonObject.getString("desc_simplenews");
String time_simplenews = jsonObject.getString("time_simplenews");
String date_simplenews = jsonObject.getString("date_simplenews");
p = new Simplenews_data();
p.setId_simplenews(id_simplenews);
p.setName_simplenews(name_simplenews);
p.setImage_simplenews(image_simplenews);
p.setDesc_simplenews(desc_simplenews);
p.setTime_simplenews(time_simplenews);
p.setDate_simplenews(date_simplenews);
post_array2.add(p);
I have searched and found this code that works for other issue if u have to compare two integers :
Collections.sort(post_array, new Comparator<Standings_data>(){
public int compare(Standings_data s1, Standings_data s2) {
return s1.getPts().compareToIgnoreCase(s2.getPts());
}
});
But really i don 't have any idea how to sort it by this date format so when a news come it shows in top of recyclerview not randomly.
This a simple screenshot of the current situation:
Extract year, month and day by spliting your String :
String[] parts = date.split("/");
Convert into Integers then compare year, month and day.
Should works.
(Vucko answer is better if you can parse with SimpleDateFormat)
You could convert the Strings to Dates like Vucko recommends, or you could convert the dates to ISO 8601 format and sort them alphabetically.
ISO 8601 looks like YYYY-mm-dd so alphabetically sorting these as strings will sort by year, month, then day, which effectively sorts the strings chronologically.
isodate = date.subString(5) + date.subString(0,2) + date.substring(3,4)
This will leave you with an edge case of dates with 1 or 2 numbers (7 vs 17) but that should hopefully encourage you to use a better date format. You can find out how to sort the ArrayList here Sorting a collection of objects

How to use orderBy when DATE is stored in String format [duplicate]

This question already has answers here:
Firebase query by date string
(2 answers)
Closed 5 years ago.
Using Firebase, the Date is stored as : dd/MM/yyyy in the Firebase DB in String format.
I'm not getting desired results when using orderBy to order my entries by date.
dbInstance.orderByChild("eventDate").startAt(currentDate).addListenerForSingleValueEvent(eventListener);
This is what I'm using to display entries. It works fine. But the problem is with dates not being sorted correctly.
So, if today is 02/05/17 , entry with date in the above image won't display because on comparing these two strings, the one in the image is smaller.
How can this be corrected? Please help!!
The best practice is to save your data as a TIMESTAMP like this: ServerValue.TIMESTAMP and not as a String.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("time", ServerValue.TIMESTAMP);
ref.child("yourNode").updateChildren(map);
And to get the data back, i suggest you use this method:
public static String getTimeDate(long timeStamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timeStamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
To solve your problem, you only need to create a query based on the correct DatabaseReference and than orderByValue("timestamp");
Hope it helps.

how to query with ormlite by using ISO8601 date formats in android

Hi i want to query for all of the rows/objects in the db table that have have a timeStamp in ISO8601, bigger than a date baseDate(ISO8601) , Im using the Ormlite as framework,so please suggest a solution that uses Ormlite.
Here is a simple example of my model.
#DatabaseTable(name="testTable")
class testTable
{
#DatabaseField(id = true)
int id
#DatabaseField
String timeStamp
}
Thanks
Try to use :
private TimeStampType timeStamp;
As the data type and "QueryBuilder" with a where clause.

android database delete row by content

Hey Guys ive got a problem with my database.
iam displaying my database in a textview looking like:
hh:mm dd:MM:yyyy text
12:14 12.12.2014 awdawdawd
13:12 13:12:2015 awdaw awdw
onclick iam getting the text by:
StringBuilder ortsplit = new StringBuilder();
String item = ((TextView) view).getText().toString();
String[] itemsplit = item.split("\\s+");
String uhrsplit = itemsplit[0].toString();
String datumsplit = itemsplit[1].toString();
ortsplit.setLength(0);
for (int i = 2; i < itemsplit.length; i++) {
ortsplit.append(" " + itemsplit[i].toString());
}
String sortsplit = String.valueOf(ortsplit);
then iam opening my database:
datasource.open();
datasource.findedel(uhrsplit,datumsplit,sortsplit);
datasource.close();
my datasource.findedel:
public void findedel(String pZeit, String pDatum, String pOrt) {
database.delete("TABELLE", "UHRZEIT="+Zeit +"AND DATUM="+Datum+"AND ORT="+Ort,null);
}
ive got no "id" displayed in the rows, earlier it looked like:
1 hh:mm dd:MM:yyyy text
2 12:14 12.12.2014 awdawdawd
3 13:12 13:12:2015 awdaw awdw
and ive just took the "id" and searched my entries for that id = id and deleted the row, but since i deleted the first row i want to search the row by the content.
any1 got a solution for my problem?
You have multiple errors and also you are prone to SQL injection.
You must use prepared statements or you must add quotes to your strings and escaping the quotes the string has, for example, in your code:
database.delete("TABELLE", "UHRZEIT="+Zeit +"AND DATUM="+Datum+"AND ORT="+Ort,null);
this: DATUM="+Datum+"AND is bad coded, there is not space between Datum and AND so, if datum is equal to test, then you string will be like this: DATUM=testAND. That will return syntax errors in mysql, and also string must be quoted like this: DATUM='test' AND.
The main problem of quoting this way is that if Datum has quotes by itself, you will have errors too. For example, if Datum equals to te'st then your string is going to be like this: DATUM='te'st' AND. As you see, you will have 3 quotes and then will return syntax error.
You must read and understand this before going further, because you will end up with a really messy code plenty of errors and vulnerabilities: http://wangling.me/2009/08/whats-good-about-selectionargs-in-sqlite-queries.html
Good luck ;)
And also, in Java all variable names must start in lowercase (Instead of String Datum use String datum)

Query a database with a string that contains "/"

I store a date in my database format "MM/dd/yyyy" and I want to do a query by a specific date but when I make the query the cursor returns nothing.
Is it because of the "/" that is in the string or something else? And yes I know the date is stored properly in the database
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(getActivity(),Games.GAMES_URI,new String[] {Games.GAMES_ID},Games.GAMES_DATE + "="+dt,
null,null);
}
converting the date
public convertDate(Calendar date){
mDate = date;
Date d = new Date(date.getTimeInMillis());
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
dt = df.format(d);
}
The query you are trying to do will look like:
... WHERE games_date=08/11/2012
where it needs to be:
... WHERE games_date="08/11/2012"
(assuming that games_date is the name of the column -- replace as needed)
Try Games.GAMES_DATE + "=?" for your fourth CursorLoader constructor parameter, and {dt} for your fifth CursorLoader constructor parameter, and Android/SQLite will automatically add your quotation marks for you where needed, assuming that your ContentProvider is backed by SQLite.
Also, you might consider storing your date in some other format. If you want it to be a string, yyyy-MM-dd (or yyyy/MM/dd) is a better choice, as it will sort correctly in chronological order. If you do not need it to be a string, just storing getTimeInMillis() in an INTEGER column will make it easier to convert to and from Date objects without messing with string conversions.

Categories

Resources