Trying to Parse Instagram JSON - android

My app is crashing when trying to parse Instagram JSON. What am I doing wrong here?
public class InstagramActivity extends BaseActivity {
static String url;
static ArrayList<String> thumbnailURLS;
static ArrayList<String> standardURLS;
static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
context = getApplicationContext();
getActionBar().setTitle("Instagram");
url = "https://api.instagram.com/v1/users/1373666362/media/recent/?client_id=a2b04732b52d43c99fe453a8ca2a5512&count=50";
thumbnailURLS = new ArrayList<String>();
standardURLS = new ArrayList<String>();
new ParseJSON().execute();
}
public static class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser()
{
}
public JSONObject getJSONFromUrl(String jsonUrl)
{
// Making HTTP request
try
{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(jsonUrl);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try to parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
public static class ParseJSON extends AsyncTask<Void,Void,ArrayList> {
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// get json from url here
JSONObject json = jParser.getJSONFromUrl(url);
try {
JSONArray dataArray = json.getJSONArray("data");
int thumbnailsCount = dataArray.length();
for (int i = 0; i < thumbnailsCount; i++) {
JSONObject imagesObject = dataArray.getJSONObject(i).getJSONObject("images");
String thumbURL = imagesObject.getJSONObject("thumbnail").getString("url");
thumbnailURLS.add(thumbURL);
}
}
catch (Exception e) {
e.getMessage().toString();
}
return thumbnailURLS;
}
#Override
protected void onPostExecute(ArrayList result) {
super.onPostExecute(result);
for (String thumb : thumbnailURLS) {
System.out.println(thumb);
}
}
}
}
It catches a JSONException
E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
and
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
This is NULL. JSONObject json = jParser.getJSONFromUrl(url);
Here is some of the expected JSON.
{
"pagination": {
"next_url": "https://api.instagram.com/v1/users/1373666362/media/recent?access_token=25320296.1fb234f.b797e861c2494059b6584ac9749208fe&count=2&max_id=791341826737262101_1373666362",
"next_max_id": "791341826737262101_1373666362"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"kystatefair"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Amaro",
"created_time": "1408648864",
"link": "http://instagram.com/p/r-MuYWFU96/",
"likes": {
"count": 5,
"data": [
{
"username": "tayworthington_",
"profile_picture": "http://photos-g.ak.instagram.com/hphotos-ak-xaf1/10632550_835588266460870_765781001_a.jpg",
"id": "24471760",
"full_name": "τᎯϓιΘર"
},
{
"username": "renee_laurent",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_407687505_75sq_1397913189.jpg",
"id": "407687505",
"full_name": "Renee Laurent"
},
{
"username": "kystatefair",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_381460857_75sq_1396983015.jpg",
"id": "381460857",
"full_name": "kystatefair"
},
{
"username": "jennaharrod1",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xfa1/10665605_1495839117327497_809128971_a.jpg",
"id": "18591399",
"full_name": "Jenna Harrod"
}
]
},
"images": {
"low_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_a.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_s.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_n.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1408648864",
"text": "Congratulations to The Lindsey Family for winning the Gospel Quartet competition! #kystatefair",
"from": {
"username": "kyfarmbureau",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"id": "1373666362",
"full_name": "Kentucky Farm Bureau"
},
"id": "792126548887293629"
},
"user_has_liked": false,
"id": "792126548258148218_1373666362",
"user": {
"username": "kyfarmbureau",
"website": "",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"full_name": "Kentucky Farm Bureau",
"bio": "",
"id": "1373666362"
}
},
{
"attribution": null,
"tags": [
"kfbmtc"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1408555318",
"link": "http://instagram.com/p/r7aTLelU4V/",
"likes": {
"count": 4,
"data": [
{
"username": "corkey_cole",
"profile_picture": "http://photos-e.ak.instagram.com/hphotos-ak-xaf1/10598220_490230854445140_2139881142_a.jpg",
"id": "324166968",
"full_name": "corkey_cole"
},
{
"username": "renee_laurent",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_407687505_75sq_1397913189.jpg",
"id": "407687505",
"full_name": "Renee Laurent"
},
{
"username": "silveradomafia04",
"profile_picture": "http://photos-e.ak.instagram.com/hphotos-ak-xfa1/914483_1500860143488988_1771984176_a.jpg",
"id": "1006562558",
"full_name": "Gideon Bailey"
},
{
"username": "sharelouisville",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_1302605134_75sq_1399019203.jpg",
"id": "1302605134",
"full_name": "Share Louisville"
}
]
},
"images": {
"low_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_a.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_s.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_n.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1408555318",
"text": "Media is starting to crowd around for #kfbmtc",
"from": {
"username": "kyfarmbureau",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"id": "1373666362",
"full_name": "Kentucky Farm Bureau"
},
"id": "791341827391573199"
},
"user_has_liked": false,
"id": "791341826737262101_1373666362",
"user": {
"username": "kyfarmbureau",
"website": "",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"full_name": "Kentucky Farm Bureau",
"bio": "",
"id": "1373666362"
}
}
]
}
UPDATE: The problem appears to be with the Instagram api url I'm using isn't giving me the JSON. I think it may be because I'm using my client_id instead of getting an access token. Does anyone know if that is the case? I used a JSON URL from something else that I know doesn't require an access token and it returned the JSON just fine.

I have updated your method getJSONFromUrl, which can be seen below:
The problem is that, the server is returning 405 means method not allowed. You was using POST to access the data, which this server does not allow. You have to use GET here for a successful request.
Rest of your code is working fine.
You can update the code below to add a default case where you can return a valid constant json string with a message that can avoid app crash, as well you can add other cases like 404 and 405 and return a valid json with an appropriate message that is suitable to the user to understand.
public JSONObject getJSONFromUrl(String jsonUrl)
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(jsonUrl);
String responseBody = "DEFAULT_MSG_TEXT";
int resCode = 0;
try{
HttpResponse response = client.execute(get);
int responseCode = response.getStatusLine().getStatusCode();
resCode = responseCode;
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
break;
}
}
catch(Exception ex){
Log.e("Post Error",resCode + "\n Exception" + ex);
responseBody = "DEFAULT_MSG_TEXT";
}
json = responseBody;
// try to parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Try this and let me know !!!

Related

Android - Getting value from the JSON object

I have this json
{
"results": [
{
"user": {
"gender": "male",
"name": {
"title": "mr",
"first": "herbert",
"last": "davidson"
},
"location": {
"street": "9763 fincher rd",
"city": "melbourne",
"state": "new south wales",
"zip": 26278
},
"email": "herbert.davidson#example.com",
"username": "lazyelephant581",
"password": "abgrtyu",
"salt": "O8ZbSsUL",
"md5": "7575bd959be09bc6d510a6a91750ce40",
"sha1": "0db99de8402e1defbd7935dbd602d99329698d4d",
"sha256": "c283d262115f90b729bb555db3dbecc8d27eebed513d7f01da799dec9e9d3269",
"registered": 1275070071,
"dob": 122409280,
"phone": "05-5742-3228",
"cell": "0481-652-548",
"TFN": "973720989",
"picture": {
"large": "https://randomuser.me/api/portraits/men/24.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/24.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/24.jpg"
}
}
}
],
"nationality": "AU",
"seed": "0a69317ece7072e000",
"version": "0.7"
}
and im doing this:(result is the json returned from the service)
try{
JSONObject jsonResponse = new JSONObject(result);
JSONObject jo = jsonResponse.getJSONObject("user");
String nome = jo.getString("username");
}catch(Exception e) {
e.printStackTrace();
}
but gives me this error
org.json.JSONException: No value for username
What im doing wrong? I tryed to do a JSONArray, tryed to get the jsonobject from another jsonobject, but giver an error that cannot convert jsonobject to a jsonarray.
regards!
Rafael
Try this in your code .
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject jo = results.getJSONObject(i);
JSONObject user = jo.getJSONObject("user");
String username = user.optString("username");
}
} catch (JSONException e) {
e.printStackTrace();
}
Use optString in your code .If your username is null,it will not return error .
The first-level key in your dictionary is "results", not "user". Also, results is an array, so you have to index into that.
You're trying to access: user->username
You need to access: results[0]->user->username

After Getting object/array from json, how can i shuffle it (Randomize)

I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}

Reading JSON data using GSON

I spent the past 4 hours looking at various answers and other resources but I simply can't wrap my head around JSON parsing. I need some help.
Here is the JSON string:
{
"success": true,
"categories": [
{
"category_id": "20",
"parent_id": "0",
"name": "Desktops",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "25",
"parent_id": "0",
"name": "Components",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "34",
"parent_id": "0",
"name": "MP3 Players",
"image": "***",
"href": "***",
"categories": null
}
]
}
Here is my Data class:
public class Data
{
String success;
List<Category> categories;
// Various get/set functions and a toString override
public class Category
{
String category_id;
String name;
String image;
// Various get/set functions
}
}
Here is where I'm trying to read this:
private class GetJson extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String results = "Fail";
URL url = null;
try
{
url = new URL("***");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
URLConnection ucon = null;
try
{
ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(is));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
{
result += line;
}
Data data = new Gson().fromJson(result, Data.class);
result = data.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return results;
}
protected void onPostExecute(String result)
{
Toast.makeText(con, result, Toast.LENGTH_SHORT);
}
}
I'm not getting anything on the stacktrace at all. I checked ADB several times. Everything seems to be working but I get no Toast or error message.
What am I doing wrong?
you forgot to show your Toast
try this
Toast.makeText(con, result, Toast.LENGTH_SHORT).show();
lol
and further
Data data = new Gson().fromJson(result, Data.class);
result = data.toString();
return result; // need return this
otherwise will always get "Fail"
//First generate getter setter of data class variables.
TypeToken<Data> tokenPoint1 = new TypeToken<Data>() {};
//SYSO result string here for Confirmation
Gson gson = new Gson();
Data dataobj= gson.fromJson(result, tokenPoint1.getType());
// syso dataobj.getname();
//Hope this will work for you

Not able to retrieve all the json values in android using a url

I am trying to retrieve json data using a url in android. My json array is as follows. I have used the below coding but the problem is that I am getting the length of jarray as equal to 1 though the array has more values in it. Secondly I am getting the length of newarr equal to 15 but the same values are getting displayed 15 times i.e id =1 is displayed 15 times. I have posted the codes down and as I am very new to json please tell me step by step where I am going wrong.
[
{
"items": [
{
"id": "11",
"Item_Id": "123",
"Item_Name": "Chicken Cream Soup",
"Price": "8",
"Currency": "AED",
"Category": "Soup",
"Description": "Creamy Chicken Soup with garnish & side helpings",
"Unit": "2",
"food_type": "Non",
"Image_Large": "/images_large/chickensoup.jpg",
"Image_Thumb": "/images_large/chickensoup.jpg",
"Timestamp": "6/23/2014 9:49:43 PM",
"Promotion": "",
"Item_Name_arabic": "حساء الطماطم",
"Item_Name_russian": "",
"Currency_arabic": "درهم",
"Currency_russian": "",
"Description_arabic": "حساء الطماطم",
"Description_russian": "",
"Note": "",
"Nutritional_info": "",
"extrafield_1": "",
"extrafield_2": "",
"preferncess": [
"No Salt",
"Extra Sugar"
],
"preferncess_ids": [
"1",
"2"
],
"price": [
"4",
"5"
],
"preferncess_arabic": [
"لا الملح",
"سكر اضافية"
]
},
{
"id": "12",
"Item_Id": "501",
"Item_Name": "Pasta Napolitan",
"Price": "18",
"Currency": "AED",
"Category": "Pasta",
"Description": "Pasta in Napolitan Sauce",
"Unit": "20",
"food_type": "Non",
"Image_Large": "/images_large/pasta.jpg",
"Image_Thumb": "/images_large/pasta.jpg",
"Timestamp": "6/23/2014 9:47:45 PM",
"Promotion": "",
"Item_Name_arabic": "حساء الطماطم",
"Item_Name_russian": "",
"Currency_arabic": "درهم",
"Currency_russian": "",
"Description_arabic": "حساء الطماطم",
"Description_russian": "",
"Note": "",
"Nutritional_info": "",
"extrafield_1": "",
"extrafield_2": "",
"preferncess": [
"No Salt"
],
"preferncess_ids": [
"3"
],
"price": [
"5"
],
"preferncess_arabic": [
"لا الملح"
]
},
//some more values till id=25
"categories": [
{
"categoryName": "Salads",
"categoryShortName": "Salads",
"catid": "0",
"categoryArabicName": "سلطة خضراء"
},
{
"categoryName": "Mezzah",
"categoryShortName": "Mezzah",
"catid": "1",
"categoryArabicName": "المزة"
},
//some more values till id=25
"questions": [
{
"q_id": "1",
"q_question": "How would you rate our Menu ?",
"q_option1": "Excellent",
"q_option2": "Very Good",
"q_option3": "Good",
"q_option4": "Bad",
"q_option5": "Terrible",
"Timestamp": "9/12/2013 3:31:55 PM",
"q_status": "1"
},
{
"q_id": "2",
"q_question": "How would you rate our presentation, taste and quality of food ?",
"q_option1": "Excellent",
"q_option2": "Very Good",
"q_option3": "Good",
"q_option4": "Bad",
"q_option5": "Terrible",
"Timestamp": "9/12/2013 3:31:55 PM",
"q_status": "1"
},
//some more values here
Json parsing code
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://166.62.17.208/json_preferencess.aspx");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success "+"nameValuePairs");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("log_tag", "result "+result.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
String s="",s1,s2,s3,s4,s5,s6,s7,s8,s9;
Log.w("Lengh",""+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONArray newarr = jArray.getJSONObject(i).getJSONArray("items");
Log.w("Lengh",""+newarr.length());
for(int j= 0; j<newarr.length();j++){
JSONObject json_data = newarr.getJSONObject(i);
s=json_data.getString("id");
s1=json_data.getString("Item_Id");
Log.i("json display",""+s+""+s1);
}
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
try this way
public String postData(String url, List<NameValuePair> nameValuePairs)
throws Exception {
// Getting the response handler for handling the post response
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(url);
// Setting the data that is to be sent
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
String response = httpClient.execute(postMethod, res);
Log.i(TAG , "response :: "+response);
return response;
}
For json.
rootObject = new JSONObject(postData(url,nameValuesPair));

How to Sort JSON Array from JSON Objects in Android?

I have a JSON array, and I want to sort it Depending on the name and too alphabetically.
My Json is as follows.
[
{
"UserID": 77,
"InvID": 333,
"Email": "sumeetssm#gmail.com",
"Phone": "",
"Name": "Summet",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 334,
"Email": "amit#testt.com",
"Phone": "",
"Name": "Amit",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 3,
"InvID": 335,
"Email": "amitesh#yahoo.com",
"Phone": "",
"Name": "Amitesh",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 336,
"Email": "foobar#test.com",
"Phone": "",
"Name": "FOO",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 337,
"Email": "krazy.lance#gmail.com",
"Phone": "",
"Name": "Krazy",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 1,
"InvID": 338,
"Email": "test#yahoo.com",
"Phone": "",
"Name": "Test",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 339,
"Email": "maktest#yahoo.com",
"Phone": "",
"Name": " ",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 340,
"Email": "Sam#rediff.com",
"Phone": "",
"Name": "SAM",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 101,
"InvID": 343,
"Email": "anurag#yahoo.com",
"Phone": "",
"Name": "Anurag",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 95,
"InvID": 379,
"Email": "s#s.com",
"Phone": "",
"Name": "S",
"Company": "",
"Date": "2014-01-14T00:00:00"
},
{
"UserID": 0,
"InvID": 428,
"Email": "sumeetssm#yahoo.com",
"Phone": "",
"Name": "Summet",
"Company": "",
"Date": "2014-01-16T00:00:00"
},
{
"UserID": 4,
"InvID": 494,
"Email": "sameer#iconnectgroup.com",
"Phone": "",
"Name": "Sameer P",
"Company": "",
"Date": "2014-01-21T00:00:00"
},
{
"UserID": 85,
"InvID": 507,
"Email": "jonny#dep.com",
"Phone": "9404988188",
"Name": "Jonny Dep",
"Company": "Iconnect",
"Date": "2014-01-22T00:00:00"
}
]
As you can see I have a key value "Name" and in that I get respected names. I want to sort this Json array completely based on this names and that too alphabetically.Thanks in advance.
Convert JSONArray to Arraylist<JSONBbject> and use Collections to sort your arraylist
for example :
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
try {
array.add(jsonArray.getJSONObject(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
return (lhs.getString("Name").toLowerCase().compareTo(rhs.getString("Name").toLowerCase()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
Firstly, parse the json data and add every json object to List of Object (e.g. Employee)
List<Employee> employees = parseJson(jsonDate);
Collections.sort(employees, new EmployeeComparator());
Here is the comparator implementation:
class EmployeeComparator implements Comparator<Employee> {
#Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
// try this way i have gave demo code you have modify as per your requirement.
public class MyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","Haresh");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name","Akash");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name","Biraj");
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("name","Salim");
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("name","Saloni");
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject);
jsonArray.put(jsonObject3);
jsonArray.put(jsonObject2);
jsonArray.put(jsonObject4);
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)toList(jsonArray);
Collections.sort(list,new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> stringStringHashMap, HashMap<String, String> stringStringHashMap2) {
return stringStringHashMap.get("name").compareTo(stringStringHashMap2.get("name"));
}
});
for (HashMap<String,String> row : list){
System.out.println("Row :"+row.get("name"));
}
}catch (Exception e){
e.printStackTrace();
}
}
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
public Map<String, String> jsonToMap(JSONObject object) throws JSONException {
Map<String, String> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)).toString());
}
return map;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
private List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
}
JSONArrays are not sortable. You can extract the data into an ArrayList and then sort with a comparator and then put back into the JSONArray.
On the Android side you generally won't sort objects in JSON format. If they do need to be sorted before you retrieve them, that is something that should occur on the backend.
Alternatively, and this is very common, you will parse the JSON objects into local Java objects (or Collections of objects), and then you can use a comparator to sort the collection based on a certain property that exists within all objects in the collection.
Fortunately both of these tasks have been asked and answered many times before. For more information on parsing JSON see How to parse JSON in Android. For more information on sorting objects in a collection see Android-java- How to sort a list of objects by a certain value within the object.

Categories

Resources