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

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

Related

How to filter the recyclerlistview in android

Hi in the code I am using recyclerview to displaying a listview .I am calling the APi and rending the list .But in that list contains data are chnaging with the content.
I want to filter the list and display it into single list item
For example list items contains name and details and unique no.want to display all the contents are name
sample json response:
"blocks": [
{
"label": "Basic Information",
"fields": [
{
"name": "sales_stage",
"value": "Opportunity",
"label": "Sales Stage",
"uitype": "15",
"type": {
"defaultValue": null
}
},
{
"name": "potentialname",
"value": "GVN hospital-Falco",
"label": "Opportunity Name",
"uitype": "2",
"type": {
"defaultValue": null
}
},
{
"name": "assigned_user_id",
"value": {
"value": "19x84",
"label": "Chandra Mouli N"
},
"label": "Assigned To",
"uitype": "53",
"type": {
"defaultValue": {
"value": "19x1",
"label": "Administrator"
}
}
},
{
"name": "potential_no",
"value": "GW/OPP/100743",
"label": "Opportunity Number",
"uitype": "4",
"type": {
"defaultValue": null
}
}
{"label": "Products",
"fields": [
{
"name": "productid",
"value": {
"value": "14x33080",
"label": "CS 30"
},
"label": "Item Name",
"uitype": "10",
"type": {
"defaultValue": null
}
},]
}
]
}]
"blocks": [
{
"label": "Basic Information",
"fields": [
{
"name": "sales_stage",
"value": "Opportunity",
"label": "Sales Stage",
"uitype": "15",
"type": {
"defaultValue": null
}
},
{
"name": "potentialname",
"value": "GVN hospital-Falco",
"label": "Opportunity Name",
"uitype": "2",
"type": {
"defaultValue": null
}
},
{
"name": "assigned_user_id",
"value": {
"value": "19x84",
"label": "Chandra Mouli N"
},
"label": "Assigned To",
"uitype": "53",
"type": {
"defaultValue": {
"value": "19x1",
"label": "Administrator"
}
}
},
{
"name": "potential_no",
"value": "GW/OPP/100743",
"label": "Opportunity Number",
"uitype": "4",
"type": {
"defaultValue": null
}
}]
{"label": "Products",
"fields": [
{
"name": "productid",
"value": {
"value": "14x33080",
"label": "CS 30"
},
"label": "Item Name",
"uitype": "10",
"type": {
"defaultValue": null
}
},]
}]
Actual output:
example: list1:
name :xyz
product:123
list2:
name :xyz
product:abc
list3:
name :xyz
product:1234
Expected output:
list:
name :xyz
product:123,abc,1234
Java:
private void fetchJSONForSales(){
handler.postDelayed(new Runnable() {
#Override
public void run() {
sessionId = getActivity().getIntent().getStringExtra("sessionId");
String operation = "syncModuleRecords";
String module = "Potentials";
String syncToken="";
String mode="public";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<SyncModule> call = service.GetSyncModuleList(operation, sessionId, module,syncToken,mode);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<SyncModule>() {
#Override
public void onResponse(Call<SyncModule> call, Response<SyncModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
SyncModule syncModule = response.body();
String success = syncModule.getSuccess();
if (success.equals("true")) {
SyncResults results = syncModule.getResult();
Sync sync=results.getSync();
ArrayList<SyncUpdated> syncUpdateds=sync.getUpdated();
for(SyncUpdated syncUpdated:syncUpdateds){
ArrayList<SyncBlocks> syncBlocks=syncUpdated.getBlocks();
String title = "";
String value = "";
String potentialValue = "";
String potentialNo = "";
String assigned = "";
String contact = "";
String location = "";
String related = "";
String winprobValue = "";
String valueAndQty = "";
String productValue = "";
String quantity = "";
String salesstageValue="";
String employee="";
String leadsource="";
String remark_sales_person="";
String segment="";
String modality="";
String circle="";
String prospect_type="",equ_details="",sale_type="",createdtime="",modifiedtime="",modifiedby="",closingdate="",exp_delivery_date="",pndt="",demo_done="",s_i="",demo_date="",fun_req="",site_read="",
support_person="",support_type="",opportunity_type="",department="",rating="",interest_type="",
txt_adj="",hdnS_H_Amount="",pre_tax_total="",hdnSubTotal="",listprice="",comment="",discount_amount="",tax1="",tax2="",tax3="",lost_reason="",
competition_name="",price_quoted="",general_remark="",description="",termsnconditions="";
String mobie = sharedPreferences.getString("mobiles", null);
for (SyncBlocks syncBlocks1 : syncBlocks) {
String label = syncBlocks1.getLabel();
//Basic Information
if (label.equals("Basic Information")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("sales_stage")) {
salesstageValue = String.valueOf(values);
} else if (name.equals("potentialname")) {
potentialValue = String.valueOf(values);
} else if (name.equals("assigned_user_id")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
// assigned_tos.add(v);
assigned = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("related_to")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
// assigned_tos.add(v);
related = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("contact_id")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
contact = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("potential_no")) {
potentialNo = String.valueOf(values);
} else if (name.equals("location")) {
location = String.valueOf(values);
}else if (name.equals("employee")) {
employee = String.valueOf(values);
}else if (name.equals("leadsource")) {
leadsource = String.valueOf(values);
}else if (name.equals("cf_954")) {
remark_sales_person = String.valueOf(values);
}else if (name.equals("segment")) {
segment = String.valueOf(values);
}else if (name.equals("modality")) {
modality = String.valueOf(values);
}else if (name.equals("circle")) {
circle = String.valueOf(values);
}
}
} else if (label.equals("Opportunity Details")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("cf_996")) {
title = String.valueOf(values);
} else if (name.equals("cf_897")) {
winprobValue = String.valueOf(values);
}else if (name.equals("cf_960")) {
prospect_type = String.valueOf(values);
}else if (name.equals("cf_1010")) {
equ_details = String.valueOf(values);
}else if (name.equals("cf_992")) {
sale_type = String.valueOf(values);
}else if (name.equals("createdtime")) {
createdtime = String.valueOf(values);
}else if (name.equals("modifiedtime")) {
modifiedtime = String.valueOf(values);
} else if (name.equals("modifiedby")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
modifiedby = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
}else if (name.equals("closingdate")) {
closingdate = String.valueOf(values);
}else if (name.equals("cf_1000")) {
exp_delivery_date = String.valueOf(values);
}else if (name.equals("cf_998")) {
pndt = String.valueOf(values);
}else if (name.equals("demo_done")) {
demo_done = String.valueOf(values);
}else if (name.equals("cf_903")) {
s_i = String.valueOf(values);
}else if (name.equals("demo_date")) {
demo_date = String.valueOf(values);
}else if (name.equals("cf_899")) {
fun_req = String.valueOf(values);
}else if (name.equals("cf_1002")) {
site_read = String.valueOf(values);
}else if (name.equals("cf_1004")) {
support_person = String.valueOf(values);
}else if (name.equals("cf_1006")) {
support_type = String.valueOf(values);
}else if (name.equals("opportunity_type")) {
opportunity_type = String.valueOf(values);
}
}
}
}
String rupee = getResources().getString(R.string.Rs);
int paswd = (int) Double.parseDouble(quantity);
String qty=String.valueOf(paswd);
ModelTest modelTest = new ModelTest(potentialValue,related,assigned,contact,location,productValue,rupee.concat(valueAndQty),
potentialNo,mobie,competition_name,circle,closingdate,comment,createdtime,demo_date,demo_done,department
,description,discount_amount,equ_details,employee,exp_delivery_date,fun_req,general_remark,hdnS_H_Amount,hdnSubTotal,
interest_type,lost_reason,leadsource,listprice,modality,modifiedby,modifiedtime,opportunity_type,pre_tax_total,pndt,price_quoted,prospect_type,
rating,remark_sales_person,sale_type,support_type,s_i,segment,site_read,txt_adj,tax1,tax2,tax3,termsnconditions,winprobValue,support_person,qty,salesstageValue);
if(salesstageValue.equals("Opportunity")){
listSalesStageOpportunity.add(modelTest);
opportunityAdapter.notifyDataSetChanged();
As you are passing the complete model class i.e "modelTest object" to the adapter by adding it to "listSalesStageOpportunity list". All you have to change is your layout. Inflate the recycler view for item containing the names only that you want to show. If you are creating different textviews in recycler view for each data then you just need to setVisibility to View.VISIBLE for names only or you can do so by declaring it in XML layout.
HI you need to add the check there where do you want to select the name
if("name").equals.("xyz"){
append("data yo want to append")
}

Get object inside array with volley

I'm trying to retrieve the objects inside a json array such as id and brand within creditcard.
{
"result_count": "2",
"total_no_of_rows": "2",
"status": {
"status_code": "-1",
"status_text": "Success"
},
"cards": [
{
"creditCard": {
"id": "CRC-9C7I2BGN8RJY",
"brand": "AMEX",
"first6": "376449",
"last4": "3005",
"store": true
},
"method": "CREDIT_CARD"
},
{
"creditCard": {
"id": "CRC-FXDA9E2YCWWQ",
"brand": "ELO",
"first6": "636297",
"last4": "7013",
"store": true
},
"method": "CREDIT_CARD"
}
]
}
I'm using the request below unsuccessfully because it returns card with no values.
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url, null, response -> {
arrayData.clear();
try {
JSONArray cards = response.getJSONArray("cards");
for (int i = 0; i < cards.length(); i++) {
JSONObject token = cards.getJSONObject(i);
CardList card = new CardList(
token.getString("id"),
token.getString("brand"),
token.getString("first6"),
token.getString("last4"),
token.getBoolean("store"));
arrayData.add(card);
}
Log.v("arrayData", String.valueOf(arrayData));
} catch (JSONException e) {
Log.v("arrayDataError", String.valueOf(e));
e.printStackTrace();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("arrayDataError", String.valueOf(error));
}
});
Could someone help? Thanks.
Follows the solution for those who need it:
JSONArray cards = response.getJSONArray("cards");
for (int i = 0; i < cards.length(); i++) {
JSONObject token = cards.getJSONObject(i);
JSONObject creditCard = token.getJSONObject("creditCard");
card_method = token.getString("method").equals("CREDIT_CARD") ?
getString(R.string.creditcard) : getString(R.string.debitcard);
CardList card = new CardList(
creditCard.getString("id"),
creditCard.getString("brand"),
creditCard.getString("first6"),
creditCard.getString("last4"),
creditCard.getBoolean("store"));
arrayData.add(card);
}

Parsing some array from json and some items in it in android

i want to parse userinfo Array and some string in it. and getuserlistdata array and some string in it. please help me how to parse this response.This is my respons.
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test",
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India"
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
},
],
]
}
}
Sir, This my code.
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
String url_links = "http://192.168.0.65/hostandguest/android/viewprofile?uid=77";
Log.d("url_links: ", "> " + url_links);
String jsonStr = sh.makeServiceCall(url_links, ServiceHandler2.GET);
Log.v("Profile:", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
status = obj.getString("status");
data = obj.getString("data");
if (status.equalsIgnoreCase("false")) {
} else {
jsonarr = obj.getJSONArray("userinfo");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
String fname = c.getString("firstname");
Datein_arr.add(fname);
String id = c.getString("id");
}
jsonarr2 = obj.getJSONArray("getuserlistdata");
for (int j = 0; j < jsonarr2.length(); j++) {
JSONObject jo = jsonarr2.getJSONObject(j);
address = jo.getString("address");
Log.v("address", "" + address);
Log.v("Profile:", "777777777777777777777777777777777777");
hostimgrr2 = obj.getJSONArray("hostImage");
if (hostimgrr2.length() == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
det_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
} else {
for (int k = 0; k < hostimgrr2.length(); k++) {
JSONObject js = hostimgrr2.getJSONObject(k);
img = js.getString("images");
Log.v("img", "" + img);
if (k == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try like below code to parse JSONArray.
try {
private ArrayList<UserInfo> userInfoList = new ArrayList<UserInfo>();
JSONObject jsonObject = new JSONObject(jsonData); // jsonData is your reponse string
JSONArray userinfo = jsonData.getJSONArray("userinfo");
for(int i = 0; i < userinfo.length(); i++) {
JSONObject jObject = userinfo.getJSONObject(i);
UserInfo userInfo = new UserInfo();
userInfo.setId( jObject.getString("id") );
userInfo.setFirstname( jObject.getString("firstname") );
userInfoList.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
UserInfo class as follow.
public class UserInfo {
public String id = "";
public String firstname = "";
public String getID() {
return coursePrice;
}
public void setID(String id) {
this.id = id;
}
public String getFirstname() {
return coursePrice;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
First you have to validate your jsondata.
You can goto JSONLint to check whether your json is valid or not
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test"
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India",
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
}
]
}
]
}
}
And You are parsing a JSONObject as String.
ie, it should be obj.getJSONObject("data"); instead of obj.getString("data");
Also check for other parsing issues like this.

Trying to Parse Instagram JSON

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 !!!

Converting JSON to model object Android

I'm new to using JSON in Android and have been running into a few problems creating a model object from the JSON. If anyone knows of any good tutorials or resources that would be good to look into for more details I'd really appreciate them. I've been looking at the tutorial on Vogella and in the Bignerdranch Android book thus far.
I'm able to pull in the JSON and create a JSONobject, however my surveys aren't saving.
Here's the JSON I'm trying to parse:
[
{
"title": "Pepsi or Coke?",
"id": 1,
"questions": [
{
"id": 1,
"title": "Which pop do you prefer?",
"single_response": true,
"answers": [
{
"title": "Pepsi",
"id": 1
},
{
"title": "Coke",
"id": 2
},
{
"title": "Mountain Dew",
"id": 3
}
]
},
{
"id": 2,
"title": "What's your age?",
"single_response": true,
"answers": [
{
"title": "18-24",
"id": 4
},
{
"title": "25-34",
"id": 5
},
{
"title": "35-50",
"id": 6
},
{
"title": "50+",
"id": 7
}
]
},
{
"id": 3,
"title": "What's your political association?",
"single_response": true,
"answers": [
{
"title": "Republican",
"id": 8
},
{
"title": "Democrat",
"id": 9
}
]
}
]
}
]
I'm retrieving the json like this:
byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrl(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
And here's where I parse it:
public ArrayList<Survey> getSurveys(String apiKey) throws JSONException {
ArrayList<Survey> surveys = new ArrayList<Survey>();
try {
String url = Uri.parse(ENDPOINT).buildUpon().appendQueryParameter("auth_token", apiKey).build().toString();
String jsonString = getUrl(url);
Log.i(TAG, "Received json string: " + jsonString);
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i ++) {
JSONObject object = array.getJSONObject(i);
Log.i(TAG, "Object is: " + object.toString());
}
for (int i = 0; i < array.length(); i++) {
Survey survey = new Survey(array.getJSONObject(i));
surveys.add(survey);
Log.i(TAG, "Survey is: " + survey.toString());
}
} catch (Exception e) {
Log.e(TAG, "Survey didn't save");
}
} catch (IOException ioe) {
Log.e(TAG, "Failed to retrieve surveys: " + ioe);
}
return surveys;
}
I'm assuming that the issue is in my create survey method itself since the JSONobjects are created correctly, but the surveys aren't saving. Any idea where I'm going wrong?
public Survey(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString("id"));
if (json.has("title")) {
mTitle = json.getString("title");
}
}
As always any help is very much appreciated!
Turns out the problem was that I was trying to convert the int id that was getting sent in JSON to a UUID.
As long as the data types match up the items are created correctly.

Categories

Resources