I'm working on an API where I'm getting a JSONArray in which there reside numerous JSONobjects containing around 10 KeyValue pairs. One of them is date: 10-3-2015. I want to use this JSONArray in a sorted manner according to the date value. I've tried a various ways including TreeMap but no success yet.
A short piece of code or a thorough idea will do the work for me.
Thanks.
EDIT:
You can do sorting easily if you use model to hold element in JSONArray.Let's say you have have model Person and JSON array contains list of persons then you can traverse JSONArray and make list of persons as follows:
List<Person> persons=new ArrayList<>();
if(jsonArray!=null){
for(JSONObject person:jsonArray){
Person p=new Person();
//set properties
//.............
//add it to persons
persons.add(p);
}
}
Now you can sort list of persons as follows:
Collections.sort(persons, new Comparator() {
public int compare(Object obj1, Object obj2) {
if (!(obj1 instanceof Person) || !(obj2 instanceof Person)) {
return -1;
}
Person p1 = (Person)obj1;
Person p2 = (Person)obj2;
return p1.getAge() -p2.getAge();
}
});
Now you can use this sorted list "persons".
Related
I have a class called GradeModel2 that has 2 members: grade (as string) and sections (as list of strings). I am trying to get my GradeModel2s data from a json string that I've read from a server.
List<GradeModel2> gradeList = new ArrayList<>();
List<String> sectionsList = new ArrayList<>();
JSONObject jo = new JSONObject(json);
JSONArray grades = jo.getJSONArray("grades");
for (int i=0;i<grades.length();i++){
sectionsList.clear();
JSONObject grade = grades.getJSONObject(i);
JSONArray sections = grade.getJSONArray("sections");
Log.e("length",sections.length()+"");
for (int k=0;k<sections.length();k++)
sectionsList.add(sections.getString(k));
gradeList.add(new GradeModel2(grade.getString("grade"), sectionsList));
}
/**************/
for (GradeModel2 grade : gradeList) {
List<String> ss = grade.getSections();
for (String s : ss)
Log.e("section",grade.getGrade()+" : "+s);
}
/**************/
The retrieved json string looks like the following:
{"id":"596","privileges":"T","grades":[{"grade":"1","sections":["A","B","C"]},{"grade":"3","sections":["A","B"]},{"grade":"7","sections":["A"]},{"grade":"9","sections":["B"]},{"grade":"10","sections":["A"]}]}
The problem is that the sections list of all GradeModel2 objects is of length 1 and value A !!!
the first Log.e, one line before the inner for loop, shows that the length of the first item of the list is 3 (A,B, and C (see the json)). However, I am trying to print all the sections of each GradeModel2 object in the inner for loop in the second block, but all I see section A for all the grades!!! (see the pic)
the result of the two Log.e
What is going on? Why is this happening?
Your problem is in sectionsList. You are trying to reuse same object, so this line of code new GradeModel2(..., sectionsList); will just add reference to the same sectionsList. And because of sectionsList.clear(); you see "A" from last json section ({"grade":"10","sections":["A"]}) To fix this, you have to create new array each time in your for loop. Something like this:
for (int i = 0 ; i < grades.length() ; i++){
List<String> sectionsList = new ArrayList<>();
// ... your json code here
gradeList.add(new GradeModel2(grade.getString("grade"), sectionsList));
}
I am using Gson library for pasring json,
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
PropertyModel[] response = gson.fromJson(reader, PropertyModel[].class);
i had set all data in Araylist like
Arraylist<PropertyModel[]> model=Arraylist<PropertyModel[]>();
model.add(response);
Now My problem is i am not able to get Arraylist PropertyModel class data
Please suggest me how can get Value from ArrayList
Thanks in Advance
try this code it will probably work...
String responseString = jsonArray.toString();
Log.e("jsonArray string --->", "" + responseString);
Type listType = new TypeToken<ArrayList<ModelOneVOneListItem>>() {
}.getType();
yourArrayList = new Gson().fromJson(responseString, listType);
First add values in Arraylist . Assume your modelclass name is CorpusHeadingModel:
ArrayList<CorpusHeadingModel> lemmaHeadingList = new ArrayList<CorpusHeadingModel>();
CorpusHeadingModel headingModel = new CorpusHeadingModel();
headingModel.setLemmaWord("Apple");
headingModel.setLemmaOccurance("3");
// now add the values to the list :
lemmaHeadingList.add(headingModel);
Now, Retrive one value with list position or any number corresponding the length of lemmaHeadingList :
CorpusHeadingModel model = lemmaHeadingList.get(position);// "position" or any number value according to your lemmaHeadingList.size().
String word = model.getLemmaWord();
String countWord= model.getLemmaOccurance();
Toast.makeText(mContext, "word= " +word+" Occurance= "+ countWord, Toast.LENGTH_SHORT).show();
Output:
word= Apple Occurance= 3
Hope, It helps, to retrieve any string from a list with modelClass.
Try like this
Add in Array list
ArrayList<String>() AddList= new ArrayList<String>();
Values = jb.getString("Your value");
AddList.add(Values);
Then Convert Array List to String Array
String[] BrandNameArray = new String[AddList.size()];
BrandNameArray = AddList.toArray(BrandNameArray);
use the Array
Your way is wrong assigning Array to Arraylist change last two lines:-
change these two line in the code
Arraylist<PropertyModel[]> model=Arraylist<PropertyModel[]>();
model.add(response);
to this:-
Arraylist<PropertyModel> model = new ArrayList<PropertyModel>(Arrays.asList(response));
For getting values you can use for loop
for(int i=0 ; i<model.size() ; i++){
PropertyModel object = model.get(i); //getting single object from Arraylist
}
as we know arraylist uses index to store values we must provide it an index but when its associated with a model class, it can be done in two ways.
let me give you an example.
1) you use your arraylist in the recycler adapter and get its object value using position,
holder.name.setText(myarraylist.get(position).getName()); // for recycler adapter in "onBindViewHolder"
name.setText(myarraylist.get(position).getName());//for base adapter in getview
2) if you want to check your object values in arraylist before passing it to the adapter you can do it this way,
for (contact d :emps ){
Log.e("name object of array",d.getName()+""); // getting the required object using the instance of model class
}
where contact is the model class, which is also the type of the arraylist emps. I hope this helps you. good luck
I want to compare two ArrayList of objects and find the unmatching values from the second ArrayList based on the ids in the object.
For Example:
Person.java
private int id;
private String name;
private String place;
MainActivity.java:
ArrayList<Person> arrayList1 = new ArrayList<Person>();
arrayList1.add(new Person(1,"name","place"));
arrayList1.add(new Person(2,"name","place"));
arrayList1.add(new Person(3,"name","place"));
ArrayList<Person> arrayList2 = new ArrayList<Person>();
arrayList2.add(new Person(1,"name","place"));
arrayList2.add(new Person(3,"name","place"));
arrayList2.add(new Person(5,"name","place"));
arrayList2.add(new Person(6,"name","place"));
I want to compare the arrayList1, arrayList2 and need to find the unmatching values from the arrayList2.
I need the id values 5,6.
How can I do this?
You can use an inner loop, to check if the Person's id from arrayList2 corresponds to any Person id in the arrayList1. You'll need a flag to mark if some Person was found.
ArrayList<Integer> results = new ArrayList<>();
// Loop arrayList2 items
for (Person person2 : arrayList2) {
// Loop arrayList1 items
boolean found = false;
for (Person person1 : arrayList1) {
if (person2.id == person1.id) {
found = true;
}
}
if (!found) {
results.add(person2.id);
}
}
Look at the modifications to person class
public static class Person{
//setters and getters
#Override
public boolean equals(Object other) {
if (!(other instanceof Person)) {
return false;
}
Person that = (Person) other;
// Custom equality check here.
return this.getId() == that.getId();
}
}
Have overridden equals(Object other)
then simply do this
for (Person person : arrayList1) {
arrayList2.remove(person);
}
your answer is array list 2, it will only contain odd objects
You should iterate through the shortest ArrayList you have, so check which list is shorter and then iterate through all the indexes in that list against every index in the other list.
(This is assuming you don't have any duplicates in either list. If you do, you might want to return a list of all indexes found.)
arrayListChars=new ArrayList<>(); //[M,A,R,V,E,L]
arrayListAddChars=new ArrayList<>(); //[M,A,....coming values]
int count = 0;
for(int i=0;i
if(arrayListAddChars.get(i).equals(arrayListChars.get(i))){
count++;
}
else
{
break;
}
}
Currently working on an app that takes results from a search, parses the JSON object returned, and then adds the resulting pieces into a few ArrayLists within a class created called VenueList.
Here is the method that receives the results from the service and parses the JSON:
private static List<String> getResultsFromJson(String json) {
ArrayList<String> resultList = new ArrayList<String>();
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
resultList.add(result.getString("text"));
}
}
catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
return resultList;
}
What results of this becomes a List variable call mResults (to clarify: mResults = getResultsFromJson(restResult);. That is then used, among other places, in the following loop that puts the results into an ArrayAdapter that is used for displaying them in a ListFragment:
for (String result : mResults) {
VenueList.addVenue(result, "HELLO WORLD");
adapter.add(result);
}
I also add the result to a class called VenueList that manages the results and makes them accessible for multiple views. It essentially just holds multiple ArrayLists that hold different types of details for each venue returned in the search. The method I use to add a venue to VenueList is below (and you can see it used in the for loop above):
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
I want the addVenue method to be able to take multiple arguments and update the VenueList class. Yet, when I call the addVenue method in the for loop, I can only pass it String result (from the parameters of the loop) and can't figure out how to pass it a second argument (which should also come from the JSON parsed by getResultsFromJson) so I've used "HELLO WORLD" as a placeholder for now.
I realize getResultsFromJson only has one list returned. I need to be able to take multiple elements from the JSON object that I parse, and then add them to VenueList in the right order.
So my questions are:
1) Given the getResultsFromJson method and the for loop, how can I use the addVenue() method as designed? How do I parse multiple elements from the JSON, and then add them to the VenueList at the same time? I plan on adding more arguments to it later on, but I assume if I can make it work with two, I can make it work with four or five.
2) If that's not possible, how should the getResultsFromJson, the for loop, and the addVenue method be redesigned to work properly together?
Please let me know if you need more detail or code - happy to provide. Thank you!
EDIT - Full VenueList class:
public class VenueList {
private static ArrayList<String> venueNames;
private static ArrayList<String> venueGeos;
public VenueList() {
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
}
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
public static String getVenueName(int position) {
return venueNames.get(position);
}
public static String getVenueGeo(int position) {
return venueGeos.get(position);
}
public static void clearList() {
venueNames.clear();
venueGeos.clear();
}
}
Clarification: I will have additional ArrayLists for each element of data that I want to store about a venue (phone number, address, etc etc)
1) I don't think methods getResultsFromJson(String json) and addVenue(String name, String geo) fit your needs.
2) I would consider rewriting method getResultsFromJson(String json) to something like this:
private static SortedMap<Integer, List<String>> getResultsFromJson(String json) {
Map<Integer, String> resultMap = new TreeMap<Integer, String>();
//...
return resultMap;
}
where the number of keys of your map should be equal to the number of objects you're extracting info, and each one of them will properly have their own list of items just in the right order you extract them.
With this approach you can certainly change your logic to something like this:
// grab your retuned map and get an entrySet, the just iterate trough it
SortedMap<Integer, String> result = returnedMap.entrySet();
for (Entry<Integer, String> result : entrySet) {
Integer key = result.getKey(); // use it if you need it
List<String> yourDesiredItems = result.getValue(); // explicitly shown to know how to get it
VenueList.addVenue(yourDesiredItems);
}
public static void addVenue(List<String> yourDesiredItems) {
// refactor here to iterate the items trough the list and save properly
//....
}
EDIT -- as you wish to avoid the go-between map i'm assuming you need nothing to return from the method
First i'm providing you with a solution to your requirements, then i'll provide you with some tips cause i see some things that could smplify your design.
To save VenueList things directly from getResultsFromJSON do something like this:
private static void getResultsFromJson(String json) {
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
//FOR EXAMPLE HERE IS WHERE YOU NEED TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then...
VenueList.addVenue(name, geo, ..., etc);
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
}
This implies that your addVenue method should know receive all params needed; as you can see this is just a way (that you can consider a workaround to your needs), however as i don't know all requirements that lead you to code this model, i will point to a few things you might consider:
1. If there's a reason for VenueList class to use everything static, consider doing this:
static{
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
//....
}
private VenueList(){
}
This way you won't need to get an instance every time and also will avoid null pointer exceptions when doing VenueList.addVenue(...) without previous instantiation.
2. Instead of having an ArrayList for every characteristic in VenueList class consider defining a model object for a Venue like this:
public class Venue{
String name;
String geo;
//... etc
public Venue(){
}
// ... getters & setters
}
then if you need that VenueList class you will just have a list o Venue objects (List<Venue>), this means that instead of calling the method addVenue, you will first create a brand new instance of Venue class and will call the setter method of each characteristic, as an example of the refactored for loop from the workaround i provided you you'd be using something like this:
List<Venue> myListOfVenues = new ArrayList<Venue>();
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
// THIS WOULD REMAIN THE SAME TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then instead of calling VenueList.addVenue(name, geo, ..., etc)...
Venue v = new Venue();
v.setName(name);
v.setGeo(geo);
// ...etc
myListOfVenues.add(v);
}
// Once you're done, set that List to VenueList class
VenueList.setVenueList(myListOfVenues);
So VenueList class would now have a single property List<Venue> venueList; and would suffer minor tweeks on methods getVenueName, etc... and everything would be more readable... i hope this helps you to get another approach to solve your problem, if i still don't make my point let me know and i'll try to help you out...
if (status == 200) {
String result = EntityUtils.toString(response.getEntity());
Log.d("Response", result);
ArrayAdapter < String > adapter = new ArrayAdapter < String > (getActivity(),
android.R.layout.simple_list_item_1, result);
setListAdapter(adapter);
}
I am unable to set my response into my List. I get my response as
{
"Appointments": [{
"Name": "Kevin",
}, {
"Name": "John",
}]
}
How would i set my name parameter in the listView.
How would i set my name parameter in the listView.
At a glance. Third parameter of ArrayAdapter should be collection but you are passing only simple String. According to your JSON i recommend you:
Create own object that will represent Person with properties(name,
age, etc.)
Parse JSON and create collection of persons
Set collection to ListAdapter
Example:
public class Person {
private String name;
...
// getters and setters
#Override
public String toString() {
return this.name;
}
}
Then, you need to parse JSON and get proper data:
List<Person> persons = new ArrayList<Person>();
Person person = null;
JSONObject root = new JSONObject(sourceString);
JSONArray appointments = root.getJSONArray("Appointments");
JSONObject child = null;
for (int i = 0; i < appointments.length(); i++) {
child = appointments.getJSONObject(i);
if (child != null)
person = new Person();
person.setName(child.getString("Name"));
persons.add(person);
}
}
Then initialise ListAdapter:
new ArrayAdapter<String>(getActivity(), layout, persons);
and now you got it.
Note:
Reason why i'm overriding toString() method is that since you are using default ArrayAdapter with build-in Android layout each object in your List will be converted to String and will be shown in ListView but if i don't override toString() it won't return person's name but string representation of object that is human-unreadable string.
result is a String containing the entire response. You need to parse or split that string into the items that you want.
You need to give your adapter the items (either as a list or an array). Right now you've created an adapter but haven't provided it any data via the constructor or any setter.
I suggest you read more about ListViews and Adapters on the Android developers site.