how to sort two json array with time - java

I want to sort two json arrays stream and stream1 with respect to time together.
The record in each array with the latest time will come first.Time is formatted like value of min ago ,days ago
This is the code I have so far:
parseJsonFeed(JSONObject response) {
try {
String stream = pref.getStream();
JSONArray feedArray = response.getJSONArray(stream);
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("title"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilepic"));
item.setTimeStamp(feedObj.getString("created_at"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
String stream2 = pref.getStream2();
if (!stream2.contentEquals("none")) {
try {
JSONArray feedArray = response.getJSONArray(stream2);
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("title"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilepic"));
item.setTimeStamp(feedObj.getString("created_at"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I need to sort the arrays together to show the most recent item in each array first, then the next most recent, and so on.

Make the FeedItem class implement Comparable or Comparator (refer this). Then call :
Collections.sort(feedItem);
before calling notifyDataSetChanged()

Related

Error in reading Json response

I"m trying to to read a json response from my json feed but the log cat shows me this error.. don't know what to do... please help..
/Error - >﹕ org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
My json response from link is here...
{
"feed":[
{
"id":65,
"name":"Hissam",
"image":"http://deejay.org/feed/ironman.jpg",
"status":"Hello thi is hissam",
"profilePic":"http://deejay.org/feed/profilepic.jpg",
"timeStamp":"1403375851930",
"url":"http://google.com"
},
{
"id":65,
"name":"Hissam",
"image":"http://deejay.org/feed/cosmos.jpg",
"status":"Hello thi is hissam",
"profilePic":"http://deejay.org/feed/profilepic.jpg",
"timeStamp":"1403375851930",
"url":"http://google.com"
}
]
}
Here is my JSON code
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
Solved the issue by adding
header('Content-type:application/json');
to my PHP script. Didn't know header were that important up till now.

get data from Json array in Json array Android Java

Hello how to get data from Json Array in another Json array i have get data till attachments but attachment doesnt work, All code work till attachments how to get data from attachments I need to get "photo_75" from it
Json
"response":{
"count":3,
"items":[
{
"id":3,
"from_id":205110032,
"owner_id":-81865402,
"date":1417672154,
"post_type":"post",
"text":"jjjjASDFGHJKYTRDXCVB",
"attachments":[
{
"type":"photo",
"photo":{
"id":330414711,
"album_id":-7,
"owner_id":205110032,
"photo_75":"http:\/\/cs605116.vk.me\/v605116032\/6325\/3SwTo8j4lJ0.jpg",
"photo_130":"http:\/\/cs605116.vk.me\/v605116032\/6326\/_OZA86FO3Nw.jpg",
"photo_604":"http:\/\/cs605116.vk.me\/v605116032\/6327\/AUtB59708Nw.jpg",
"photo_807":"http:\/\/cs605116.vk.me\/v605116032\/6328\/59oAdfz9jgI.jpg",
"width":538,
"height":807,
"text":"",
"date":1399134687,
"access_key":"7297eb663de2e4e6b2"
}
}
],
"comments":{
"count":0
},
"likes":{
"count":0
},
"reposts":{
"count":0
}
},
Java
private void parseJsonFeed(JSONObject response) {
try {
JSONObject parent = response.getJSONObject("response");
JSONArray feedArray = parent.getJSONArray("items");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("post_type"));
item.setTimeStamp(feedObj.getString("date"));
// Image might be null sometimes
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
item.setStatus(feedObj.getString("text"));
All code work till there how to get data from attachments
***JSONObject response1 = response.getJSONObject("response");
feedArray = parent.getJSONArray("items");***
JSONArray feedArray1 = response1.getJSONArray("attachments");
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject feedObj1 = (JSONObject) feedArray1.get(i1);
FeedItem item1 = new FeedItem();
item.setProfilePic(feedObj1.getString("photo_75"));
}
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance
you are looking for attachments in wrong object. "attachmetnts" is property of item.
instead of
JSONArray feedArray1 = response1.getJSONArray("attachments");
use
JSONArray feedArray1 = feedObj.getJSONArray("attachments");
in your case feedObj contains item object.
to get photo :
Remove lines :
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
and change it to :
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject attachment = (JSONObject) feedArray1.get(i1);
JSONObject photo = (JSONObject) attachment.getJSONObject("photo");
item.setImge(photo);
item.setProfilePic(photo.getString("photo_75"));
item.setStatus(photo.getString("text"));
}
You can try GSON, which would directly give you a java object from your json and you would not have to parse it manually.

How to convert int Array to JSON String in Android?

I expected to find this question around, but I couldn't. Maybe I'm Googling the wrong thing.
I have a primitive integer array (int[]), and I want to convert this into a String, that is "JSON-Parseable", to be converted back to the same int[].
What have I tried :
I tried this code :
// int[] image_ids_primitive = ...
JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly.
When I printed the jSONString variable, it has the value : ["[I#40558d08"]
whereas, I expected a proper JSON String like this : {"1" : "424242" , "2":"434343"} not sure about the quotation marks, but you get the idea.
The reason I want to do this :
I want to keep track of local images (in drawable folder), so I store their id's in the int array, then I want to store this array, in the form of a JSON String, which will be later parsed by another activity. And I know I can achieve this with Intent extras. But I have to do it with SharedPreferences.
Thanks for any help!
You don't have to instantiate the JSONArray with Arrays.asList. It can take a normal primitive array.
Try JSONArray mJSONArray = new JSONArray(image_ids_primitive);
If you are using an API level below 19, one easy method would just be to loop over the int array and put them.
JSONArray mJSONArray = new JSONArray();
for(int value : image_ids_primitive)
{
mJSONArray.put(value);
}
Source: Android Developers doc
If you want a JSON array and not necessarily an object, you can use JSONArray.
Alternatively, for a quick hack:
System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));
prints out
[1, 2, 3, 4, 5, 6, 7]
which is valid JSON. If you want anything more complicated than that, obviously JSONObject is your friend.
Try this way
int [] arr = {12131,234234,234234,234234,2342432};
JSONObject jsonObj = new JSONObject();
for (int i = 0; i < arr.length; i++) {
try {
jsonObj.put(""+(i+1), ""+arr[1]);
} catch (Exception e) {
}
}
System.out.println("JsonString : " + jsonObj.toString());
// If you wants the data in the format of array use JSONArray.
JSONArray jsonarray = new JSONArray();
//[1,2,1,] etc..
for (int i = 0; i < data.length; i++) {
jsonarray.put(data[i]);
}
System.out.println("Prints the Json Object data :"+jsonarray.toString());
JSONObject jsonObject=new JSONObject();
// If you want the data in key value pairs use json object.
// i.e {"1":"254"} etc..
for(int i=0;i<data.length;i++){
try {
jsonObject.put(""+i, data[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Prints the Json Object data :"+jsonObject.toString());
itertate this through the int array and you will get the json string
JSONStringer img = null ;
img = new JSONStringer() .object() .key("ObjectNAme")
.object() .key("something").value(yourIntarrayAtIndex0)
.key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
.key("something").value(yourIntarrayAtIndex3)
.endObject() .endObject();
String se = img.toString();
Here se is your json string in string format
This code will achieve what you are after...
int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
for (int i : array) {
jsonObject.put(String.valueOf(index), String.valueOf(i));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("YOUR_TAG", jsonObject.toString());
This will give you {"3" : "203", "2" : "200", "1": "100", "4": "4578"} as a string.
Not exactly sure why its not in the exact order, but sorting by a key is quite easy.

Parse json array from webserver

I'm going to parse a json array from web server to android app.The array looks like this
{"Level":
[
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]}
]
}
my java code is
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Level");
rlevel = new ArrayList<LatLng>();
System.out.println("*****JARRAY*****"+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
jlat = json_data.getDouble("lat");
jlgn = json_data.getDouble("lgn");}
but not works! any idea?after this i want to save each route into an array (etc $plan[1]=first route from json, $plan[2]=second route from json)
Try something like this:
//code is a String where you saved the json
JSonObject json= new JsonParser().parse(code).getAsJsonObject();
JsonArray jArray= json.getAsJsonArray("Level");
rLevel=new ArrayList<LatLng>();
//notice the use of the size() method. There is not length() method defined for ArrayList
System.out.println("*****JARRAY*****"+jArray.size());
for(int i=0;i<jArray.size();i++){
//notice that inside the Level Array you have route-arrays
JSonObject level_item = jArray.get(i).getAsJsonObject();
JSonArray route= level_item.getAsJSonArray("route");
//now I don't know exactly what data you want to extract, since there are 2
//pairs of LatLng, for the first one:
jlat = route.get(0).get("lat").getAsDouble();
jlgn= route.get(0).get("lgn").getASDouble();
The exact names for methods and JsonObjects tend to differ from a library to another, but the principle is the same.
This parse task can be done very easily using droidQuery:
try {
JSONObject json = $.parseJSON(result);
if (json.has("Level")) {
Object[] datas = $.makeArray(json.getJSONArray("Level"));
for (Object data : datas) {
JSONObject obj = (JSONObject) data;
Object[] coordinates = $.makeArray(obj.getJSONArray("route"));
for (Object coord : coordinates) {
Map<String, ?> map = $.map((JSONObject) coord);
double latitude = (Double) map.get("lat");
double longitude = (Double) map.get("lgn");
//TODO: do something with these values
}
}
}
else {
Log.d("JSON", "Result does not contain 'Levels' variable");
}
}
catch (Throwable t) {
t.printStackTrace();
}

How to convert JSON formatted string of data rows of a table in to java array in android

I have a JSON string like this of data for a table in an android app. one of {} is a row of data for the table. I want to separate these {}s into an array and then each element inside this array into other sub-arrays separating other elements inside {}. Please suggest an appropriate way of accomplishing this criteria using JSON. Thank you.
[
{
"nodeName":"prime_mtsc22#smpp3",
"nodeId":"MTSC3",
"tidPrefix":"4",
"optStatus":"offline",
"daStart":"1",
"daEnd":"3",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp2",
"nodeId":"MTSC58",
"tidPrefix":"1",
"optStatus":"blocked",
"daStart":"5",
"daEnd":"10",
"description":"new description"
},
{
"nodeName":"prime_mtsc22#smpp1",
"nodeId":"MTSC1",
"tidPrefix":"15",
"optStatus":"online",
"daStart":"12",
"daEnd":"20",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp0",
"nodeId":"MTSC15",
"tidPrefix":"15",
"optStatus":"offline",
"daStart":"25",
"daEnd":"30",
"description":"Description"
}
]
ok so in that case the code to use is this
String jsonString = <your jsonString>;
// THIS IS NOT NEEDED ANYMORE
//JSONObject json = new JSONObject(jsonString);
JSONArray topArray = null;
try {
// Getting your top array
// THIS IS NOT NEEDED ANYMORE
//topArray = json.getJSONArray(jsonString);
//use this instead
topArray = new JSONArray(jsonString);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
ok?
Use JSONObject for this http://developer.android.com/reference/org/json/JSONObject.html
Example
String jsonString = <your jsonString>;
JSONObject json = new JSONObject(jsonString);
JSONObject topArray = ;
try {
// Getting your top array
topArray = json.getJSONArray(TAG_ARRAY_TOP);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use the NodePOJO class to hold each row values.
public class NodePOJO {
private String nodeName;
// do for rest of the json row data
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeName() {
return this.nodeName;
}
}

Categories

Resources