I write a program that parse json and shows it in a listView.
Now i want to sort it but don't know how and fail. In program i have a List<PoolOfflineModal> alist = new ArrayList<>();
so modal are this;
public class PoolOfflineModal {
private int id;
private String name;
private int price;
private int priceWithoutDiscount;
private String tel;
private int discountPercent;
private String address;
private String photo;
}
and data simple is here http://hayat.cloudsite.ir/pools/pools.json
so i want to sort List ascending with price, so update ListView and i don't know...
another idea?! or solution?!
another way are exist to sort ListView from a column without sort list?!?
this is my last Comparator
public class MyComparator implements Comparator<PoolOfflineModal> {
#Override
public int compare(PoolOfflineModal lo, PoolOfflineModal ro) {
int result = 0;
if (way == "name") {
result = lo.getName().compareTo(ro.getName());
} else if (way == "price") {
result = lo.getPrice().compareTo(ro.getPrice());
} else if (way == "percent") {
result = lo.getDiscountPercent().compareTo(ro.getDiscountPercent());
}
return result;
}
}
List Object Like This:
List<PoolOfflineModal> alist = new ArrayList<>();
Comparator Class Like this:
public class MyComparator implements Comparator<PoolOfflineModal> {
#Override
public int compare(PoolOfflineModal o1, PoolOfflineModal o2) {
return o1.id.compareTo(o2.id);
}
}
Use Like this:
Collections.sort(alist, new MyComparator());
Hope it will helpful to you.
Related
I'm thinking about it, but I can't print the name and age of the json Crospromotion on the console. I'm using the GSON library, but I'm stuck right now and I don't know how to move forward.
I have my JSON
{
"crospromotion": [
{
"name": "Orus",
"age":14
},
{
"name": "Michelle",
"age":29
},
{
"name": "Jack",
"age":29
}
],
"totalAccessorios": 20,
"totalCaras": 20
}
My JSon controller class:
public class Data {
private Crospromotion crospromotion;
private int totalAccessorios, totalCaras;
public int getTotalAccessorios() {
return totalAccessorios;
}
public int getTotalCaras() {
return totalCaras;
}
}
Class Crospromotion:
public class Crospromotion {
private String nombre;
private int edad;
public String getNombre() {
return nombre;
}
public int getEdad() {
return edad;
}
}
MainActivity:
Gson gson = new Gson();
final Data data = gson.fromJson(myResponse, Data.class);
Log.d("MEN: ", data.getTotalAccessorios());
// I want to print in Log, the fields Crospromotion: name and age. But I don't know how to continue.
The attributes in the json string have different names than in the class Crospromotion. So you can just change the property names of the Crospromotion class like this:
public class Crospromotion {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Also in the json string you have an array of Crospromotion instances, but in the data class you only have one instance. That means you have to change the json string or write the class like this.
import java.util.List;
public class Data {
private List<Crospromotion> crospromotions;
private int totalAccessorios, totalCaras;
public int getTotalAccessorios() {
return totalAccessorios;
}
public int getTotalCaras() {
return totalCaras;
}
public List<Crospromotion> getCrospromotions() {
return crospromotions;
}
}
You also didn't have a getter for the Crospromotion List. Therefore you couldn't access it, because the property was private. With this code you should be able to access the data that you want to access.
It looks like you just forgot to add a getter for your Crospromotion field in your Data class?
public class Data {
private List<Crospromotion> crospromotion;
private int totalAccessorios, totalCaras;
public int getTotalAccessorios() {
return totalAccessorios;
}
public int getTotalCaras() {
return totalCaras;
}
public Crospromotion getCrospromotion() {
return crospromotion;
}
}
...
Log.d("MEN: ", data.getCrospromotion().getAge());
Btw, it looks like the fields in your JSON don't match your Crospromotion class. GSON uses reflection to match json fields to members of a class. You can use #SerializedName() to map JSON field names to member fields if the names differ.
For example:
public class Crospromotion {
#SerializedName("name") private String nombre;
#SerializedName("age") private int edad;
public String getNombre() {
return nombre;
}
public int getEdad() {
return edad;
}
}
I want simple example for MVP structure in android to refresh recyclerview item not the whole list of recyclerview.
It will refresh only items in recyclerview of android.
This is a problem I've thought about quite a lot. There are two possible ways of doing it:
Pass the new List of data to the Adapter and it does the work of working out what's changed and updating the correct items.
Keep a record of the current items in your model then when the new list is calculated send ListChangeItems to the Adapter.
I'll outline both in more detail below. In both cases you need to calculate the differences between what is currently showing and the new data. I have a helper class ListDiffHelper<T> which does this comparison:
public class ListDiffHelper<T> {
private List<T> oldList;
private List<T> newList;
private List<Integer> inserted = new ArrayList<>();
private List<Integer> removed = new ArrayList<>();
public List<Integer> getInserted() {return inserted;}
public List<Integer> getRemoved() {return removed;}
public ListDiffHelper(List<T> oldList, List<T> newList) {
this.oldList = oldList;
this.newList = newList;
checkForNull();
findInserted();
findRemoved();
}
private void checkForNull() {
if (oldList == null) oldList = Collections.emptyList();
if (newList == null) newList = Collections.emptyList();
}
private void findInserted() {
Set<T> newSet = new HashSet<>(newList);
newSet.removeAll(new HashSet<>(oldList));
for (T item : newSet) {
inserted.add(newList.indexOf(item));
}
Collections.sort(inserted, new Comparator<Integer>() {
#Override
public int compare(Integer lhs, Integer rhs) {
return lhs - rhs;
}
});
}
private void findRemoved() {
Set<T> oldSet = new HashSet<>(oldList);
oldSet.removeAll(new HashSet<>(newList));
for (T item : oldSet) {
removed.add(oldList.indexOf(item));
}
Collections.sort(inserted, new Comparator<Integer>() {
#Override
public int compare(Integer lhs, Integer rhs) {
return rhs - lhs;
}
});
}
}
For this to work properly you need to ensure that the equals() method of the Data class compares things in a suitable way.
Adapter Lead
In this case your Presenter calls getData() on the model (or subscribes to it if you're using Rx) and receives List<Data>. It then passes this List to the view through a setData(data) method which in turn give the list to the Adapter. The method in the Adapter would look something like:
private void setData(List<Data> data) {
if (this.data == null || this.data.isEmpty() || data.isEmpty()) {
this.data = data;
adapter.notifyDataSetChanged();
return;
}
ListDiffHelper<Data> diff = new ListDiffHelper<>(this.data, data);
this.data = data;
for (Integer index : diff.getRemoved()) {
notifyItemRemoved(index);
}
for (Integer index : diff.getInserted()) {
notifyItemInserted(index);
}
}
It is important to remove items first before adding new ones otherwise the order will not be maintained correctly.
Model Lead
The alternative approach is to keep the Adapter much dumber and do the calculation of what has changed in your model layer. You then need a wrapper class to send the individual changes to your View/Adapter. Something like:
public class ListChangeItem {
private static final int INSERTED = 0;
private static final int REMOVED = 1;
private int type;
private int position;
private Data data;
public ListChangeItem(int type, int position, Data data) {
this.type = type;
this.position = position;
this.data = data;
}
public int getType() {return type;}
public int getPosition() {return position;}
public Data getData() {return data;}
}
You would then pass a List of these to your Adapter via the view interface. Again it would be important to have the removals actioned before the inserts to ensure the data is in the correct order.
I need deserialize a string(json) to a arraylist inside a model. I'm using the Jackson-Annotation library to do this. Anyone can help me?
I've tried this, but doesn't work:
#JsonDeserialize(as = Model.class)
private ArrayList<Model> model;
or:
#JsonDeserialize(as = ArrayModel.class) //ArrayModel extends arrayList<Model>
private ArrayList<Model> model;
Sample:
public class Model extends BaseModel {
#JsonProperty("id")
private int id;
#JsonDeserialize(as = ModelTwo.class)
private ArrayList<ModelTwo> modelTwo;
public ArrayList<ModelTwo> getModelTwo() {
return modelTwo;
}
public void setModelTwo(ArrayList<ModelTwo> modelTwo) {
this.modelTwo = modelTwo;
}
}
I've solved this!
You need say the type of Object and the type of content.
After this, you need create a new Json with properties on params.
On first model:
#JsonProperty("property")
#JsonDeserialize(as=ArrayList.class, contentAs=ModelTwo.class)
private List<ModelTwo> modelsTwo;
On second model:
#JsonCreator
public ModelTwo(
#JsonProperty("id") int id,
#JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
I'm trying to sort a list of objects in java using Collections.sort(). But I keep getting this error: type parameter is not within its bound". Does anyone know how I can remedy this problem?
My code
public List<String> fetchNumbersForLeastContacted()
{
List<String> phonenumberList = getUniquePhonenumbers();
List<TopTen> SortList = new ArrayList<TopTen>();
Date now = new Date();
Long milliSeconds = now.getTime();
//Find phone numbers for least contacted
for (String phonenumber : phonenumberList)
{
int outgoingSMS = fetchSMSLogsForPersonToDate(phonenumber, milliSeconds).getOutgoing();
int outgoingCall = fetchCallLogsForPersonToDate(phonenumber, milliSeconds).getOutgoing();
//Calculating the total communication for each phone number
int totalCommunication = outgoingCall + outgoingSMS;
android.util.Log.i("Datamodel", Integer.toString(totalCommunication));
SortList.add(new TopTen(phonenumber, totalCommunication, 0));
}
//This is where I get the error
Collections.sort(SortList);
The TopTen.class
public class TopTen {
private String phonenumber;
private int outgoing;
private int incoming;
public TopTen (String phonenumber, int outgoing, int incoming)
{
this.phonenumber = phonenumber;
this.incoming = incoming;
this.outgoing = outgoing;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public int getOutgoing() {
return outgoing;
}
public void setOutgoing(int outgoing) {
this.outgoing = outgoing;
}
public int getIncoming() {
return incoming;
}
public void setIncoming(int incoming) {
this.incoming = incoming;
}}
public static void sort (List<T> list)
This method can only be used if T inplements the Comparable interface. What implements Comparable means is that there exists a criteria by which two objects of type T can be compared and ordered. In your case, T is TopTen, which does not implement Comparable.
What you need to do:
public class TopTen implements Comparator<TopTen> {
....
....
#Override
public int compareTo(TopTen other) {
if (this == other) return EQUAL;
return this.getPhonenumber().compareToIgnoreCase(other.getPhonenumber());
}
This will compare two TopTen objects based on the phonenumber field. If you want the objects to be ordered based on another criteria, use that to return either -1 (before), 0 (equal) or 1 (after).
For example, to base the sorting on incoming, use the following:
#Override
public int compareTo(TopTen other) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == other) return 0;
if (this.getIncoming() > other.getIncoming()) {
return AFTER;
} else if (this.getIncoming() < other.getIncoming()) {
return BEFORE;
} else {
return EQUAL;
}
}
This would get you TopTen objects ordered by ascending incoming field values.
try implementing Comparable interface in TopTen class and override compareTo method to specify your sorting logic
#Override
public int compareTo(TopTen o) {
// TODO Auto-generated method stub
return 0;
}
(or)
Collections.sort(SortList, new Comparator<TopTen>(){
public int compare(TopTen t1, TopTen t2) {
return t1.phonenumber.compareTo(t2.phonenumber);
}
});
I am new to arraylist concept. Please help me how to declare arraylist and add strings and integers to it.
String str = quesid+","+k1;
ArrayList<Object> arl=new ArrayList<Object>();
arl.add("str");
In the above code the string didnt added to arraylist. Where I went wrong...plz help me
Thanks in advance...
Make a custom class, and put String and Int member fields now also make a getter() setter() methods for that fields in that class,
Now use that class in your ArrayList, Simple :-)
EDIT: Example
List<CustomClass> foo = ArrayList<CustomClass>
public class CustomClass
{
private String result;
private int count;
public CustomClass() {
super();
// TODO Auto-generated constructor stub
}
public void setResult(String res)
{
this.result=res;
}
public void setCount(int cnt)
{
this.count=cnt;
}
public String getResult()
{
return this.result;
}
public int getCount()
{
return this.count;
}
}
In your activity,
List<CustomClass> foo = ArrayList<CustomClass>
CustomClass cust = new CustomClass();
cust.setResult("Test");
cust.setCount(1);
foo.add(cust);
To retrieve data...
String res = foo.get(0).getResult();
int count = foo.get(0).getCount();
You can directly set a values by passing it to CustomClass constructor.. (In this case you have to modify constructor of CustomClass) Choice is yours.
Define a class as such:
public class StringInt{
private String s;
private int i;
public StringInt(String o1, int o2){
s = o1;
i = o2;
}
public String getString(){
return s;
}
public int getInt(){
return i;
}
public void setString(String s){
this.s = s;
}
public void setInt(int i){
this.i = i;
}
}
Then use is in an ArrayList
ArrayList<StringInt> arl = new ArrayList<StringInt>();
arl.add(new StringInt("Test", 15));
Edit: user370305 had the same idea. Great minds think alike? :P