Sort arraylist to display items by date - android

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

Related

How to fetch data between 2 dates in greenDao database

I have two dates . One is the current date and the other is 30 days back date. So I need to fetch the data between these 2 dates in Green Dao. But I am not getting the result.
MyCode:
Date startRangeDate = new Date();
Date endRangeDate = dateBefore30Days;
QueryBuilder<StructSamePage> qb = UserDao.queryBuilder();
qb.where(UserDao.Properties.dateTime.between(startRangeDate.getTime(), endRangeDate.getTime()));
List<StructSamePage> list = qb.list();
Try swapping dates you pass.
Date startRangeDate = new Date();
Date endRangeDate = dateBefore30Days;
QueryBuilder<StructSamePage> qb = UserDao.queryBuilder();
qb.where(UserDao.Properties.dateTime.between(endRangeDate.getTime(),startRangeDate.getTime() ));
List<StructSamePage> list = qb.list();
Generally between works if left hand side value is smaller than right hand side
The WhereCondition between in GreenDao uses this:
/** Creates an "BETWEEN ... AND ..." condition for this property. */
public WhereCondition between(Object value1, Object value2) {
Object[] values = { value1, value2 };
return new PropertyCondition(this, " BETWEEN ? AND ?", values);
}
So you should just have to change your dates accordingly. Because you are using NOW first and the day 30 days before later your code would do this:
Value >= NOW AND Value <= 30 DAYS BEFORE
If you use actual dates wich greenDAO does not use! Your code would look like this:
today = 2016-03-04
30DaysAgo = 2016-02-03
WHERE dateTime >= 2016-03-04 AND dateTime <= 2016-02-03
So you should be fine if you just change your order.
If you want to know more about how BETWEEN works you can read this
A word of advice: greenDao uses timestamps as INTEGERS in the database so if you use java Dates you get a Date that also has a time (when it was created) if you just remove 30 days from it you will not include the whole day 30 days ago but only the day from the time the current date object was created in time. So maybe you want to create the Date from a Calendar without a time.

Posting Json object as parameter with http

I need to post some data to a server in this format
dates: [{...},{...},{...}]
So far I have done this
for(RepeatEventItem item : selected_dates){
pEntity.addPart("dates[]", new StringBody(mapper.writeValueAsString(item)));
}
and the resulting format is this
["{...}","{...}"]
how can I get rid of the quotes as the server is expecting JSONObjects in the array not strings
You can do this with a two dimensional array
for(int i = 0; i < selectdated_dates.size(); i++){
RepeatEventItem item = selected_dates.get(i);
pEntity.addPart("dates["+i+"][]", new StringBody(mapper.writeValueAsString(item)));
}
The result will be in the format you want.

Order list of dates in String format

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);

Extract text from String

I have one String and into this string I have a url between two characters # such as "Hello world #http://thisurl# my name is Pippo" I want to take the url (http://thisurl) between two #.
How can I do ? Thanks
String data[] = str.split("#"); //spilliting string and taking into array
ArrayList<String> urlList = new ArrayList<String>();
for (int i = 0; i < data.length; i++) {
if(data[i].contains("http://"))
urlList.add(data[i]); //if string contains "http://" it means it is url save int list.
}
now you can get all uls from urlList.get(i) method.
this urlList will give you all the urls available in the string. I dint applied any null or other check. Apply it and try. If want something else try modifying content and checks.
Try String.split(). You really should be trying to google these things first.
here is an example - http://www.java-examples.com/java-string-split-example
The split method divides a string into several strings and store them into an array using a delimiter which can be defined by you.
the second element in the resulting array will be your URL

How to sort list view data which is backed with API Response and containing more then one field in each row

I want to sort data in ListView. Which contains title,description ,price at their respective position in each row. I want to implement sort functionality on title in alphabetical order. All field are stored in different array. After sorting each filed should according title. What to do? Please explain with detail example.
Create one Bean Class
Your array
array 1) title[]
array 2) description[]
for example DataBean
public class DataBean
{
String title,desc;
DataBean(String title,String desc)
{
this.title=title;
this.desc=desc;
}
}
Use this code to merge data
Create Vector;
ex: Vector vec = new Vector;
for(int i=0; i< yourArray.length; i++)
{
vec.add(title[i],description[i]);
}
Now you have vec of your date.
Just perform SORT on any field.
either title or desc.
You will get your sorted data.

Categories

Resources