i want to retrieve following filed from json object
From OriginLocation =>> CityCode, DepartureDate, DepartureTime
From DestinationLocation =>> CityCode, ArrivalTime, ArrivalDate
From Fare =>> OrigTotalFareAmt
From FlightDetails ==>> CabinClassCode, JourneyDuration
using one for loop
http://pastie.org/8563070#7
Try this.
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("Key :" + key);
System.out.println("Value :" + data.getString(key));
}
} catch (Throwable e) {
try {
System.out.println("Key :" + key);
System.out.println("Value :" + data.getString(key));
} catch (Exception ee) {
}
e.printStackTrace();
}
}
}
}
Related
I need to show a loading screen for volley, I am sending few json to the servers using volley, i written the code inside for loop for fetching a json and sending the json. But the for loop is not waiting for the responce to continue. It just completing quickly, How can i use for loop for sending jason and show the for loops value as the count of syncing.?
Code...
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
Log.d("length", String.valueOf(result.length()));
if(result.length()!=0) {
for (int e = 0; e < result.length(); e++) {
this.dialog.setMessage("Syncing "+(e+1)+" of "+result.length());
this.dialog.show();
try {
final JSONObject js = result.getJSONObject(e);
Log.d("sdfhd", js.toString());
final JSONArray ja = new JSONArray();
ja.put(js);
Log.d("sending json", ja.toString());
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, ja,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("asd", ja.toString());
Log.d("JsonArray", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject store = response.getJSONObject(i);
mydb.updateweb(store.getInt("_id"), store.getString("webid"), store.getString("regid"));
if (i == response.length() - 1) {
Toast.makeText(MainActivity.this, "Synced Successfully", Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject stor = response.getJSONObject(0);
Toast.makeText(MainActivity.this, stor.getString("result"),
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
// dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Json sdfsdfsf", js.toString());
Log.d("afs", error.toString());
Toast.makeText(MainActivity.this, "error",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
else{
Toast.makeText(MainActivity.this, "Updated Succesfully",
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
// dialog.dismiss();
}
Look at the code I have changed your logic about the dialog, also I have added success and failure counts functionality so that you can have an idea of request statuses
Global Variables:
int successCount = 0;
int failedCount = 0;
Revised onPostExecute():
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
successCount = 0;
failedCount = 0;
this.dialog.setMessage("Syncing 0 of "+result.length());
this.dialog.show();
Log.d("length", String.valueOf(result.length()));
if(result.length()!=0) {
for (int e = 0; e < result.length(); e++) {
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
try {
final JSONObject js = result.getJSONObject(e);
Log.d("sdfhd", js.toString());
final JSONArray ja = new JSONArray();
ja.put(js);
Log.d("sending json", ja.toString());
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, ja,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
boolean isCodeExecutedSuccessfully = false;
Log.d("asd", ja.toString());
Log.d("JsonArray", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject store = response.getJSONObject(i);
mydb.updateweb(store.getInt("_id"), store.getString("webid"), store.getString("regid"));
if (i == response.length() - 1) {
Toast.makeText(MainActivity.this, "Synced Successfully", Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
isCodeExecutedSuccessfully = true;
} catch (JSONException e) {
isCodeExecutedSuccessfully = false;
e.printStackTrace();
}
}
try {
JSONObject stor = response.getJSONObject(0);
Toast.makeText(MainActivity.this, stor.getString("result"),
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
// dialog.dismiss();
isCodeExecutedSuccessfully = true;
} catch (JSONException e) {
isCodeExecutedSuccessfully = false;
e.printStackTrace();
}
//////////////////////////////// DIALOG WORK ON SUCCESS ///////////////////////////////
if(isCodeExecutedSuccessfully)
++successCount;
else
++failedCount;
if((e+1) == result.length()) {
dialog.dismiss();
}
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
Log.d("::onResponse(): Status Counts", "Success=" + successCount + ", fail=" + failedCount);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//////////////////////////////// DIALOG WORK ON ERROR RESPONSE ///////////////////////////////
++failedCount;
if((e+1) == result.length()) {
dialog.dismiss();
}
Log.d("::onErrorResponse(): Status Counts", "Success=" + successCount + ", fail=" + failedCount);
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
Log.d("Json sdfsdfsf", js.toString());
Log.d("afs", error.toString());
Toast.makeText(MainActivity.this, "error",
Toast.LENGTH_SHORT).show();
//dialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
else{
Toast.makeText(MainActivity.this, "Updated Succesfully",
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
// dialog.dismiss();
}
My json response should be like this
result: [ { apps: [ { PROD_appsr12: [ { ora: [] }, { logs: [] }, { temp: [] }, {}, {}, {}, {}, {}, { pids: [] }, { admin: [] }, { portal: [] }, { appl: [] }, { rgf: [] } ] } ] } ] }
How can I parse above JSONArray in dynamically (like folder structure).
this is my code`class Getdata extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Inst_Activity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
if (pref.getString("instraw", null) != null) {
Log.e("Enter Not Null>>>", "Not Null");
spString = pref.getString("instraw", null);
jsonRes = spString;
getServerData();
} else {
Log.e("Enter Null>>>", "Yes It's Null");
ServiceHandler handler = new ServiceHandler();
jsonRes = handler.makeServiceCall(url, ServiceHandler.GET);
editor.putString("instraw", jsonRes);
editor.commit();
getServerData();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
listView.setAdapter(new ArrayAdapter<>(Inst_Activity.this,
R.layout.schema_item, R.id.textView1, list1));
}
}
private void getServerData() {
Log.e("ENTER-getServerData>>>>", "0000000");
if (jsonRes != null) {
try {
mainObj = new JSONObject(jsonRes);
Iterator<String> keys = mainObj.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.e("Main-key>>>>", key);
methFirst(key);
}
} catch (Exception e) {
}
} else {
}
}
private void methFirst(String list2) throws JSONException {
try {
Log.e("ENTER-methFirst>>>>", "1111111");
jsonArray = mainObj.getJSONArray(list2);
Log.i("MAIN-jsonArray", "" + jsonArray);
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject Obj = jsonArray.getJSONObject(j);
Log.i("MAIN-JSONObject Obj>>>>", "" + Obj);
getObjMeth(Obj);
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void getObjMeth(JSONObject subObj2) {
Log.e("ENTER-methFirst-1>>>>", "333333333333");
Log.e("ENTER-getObjMeth>>>>", "entered");
try {
Iterator<String> i_keys = subObj2.keys();
while (i_keys.hasNext()) {
String strkey = i_keys.next();
Log.e("getObjMeth-key>>>>", strkey);
list1.add(strkey);
Log.e("<<keys-list1>>", "" + list1);
sub_sub_Obj = new JSONObject();
sub_sub_Obj = subObj2;
listView.setAdapter(new ArrayAdapter<>(Inst_Activity.this,
R.layout.schema_item, R.id.textView1, list1));
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void methFirst1(String list3) {
Log.e("ENTER-methFirst-1>>>>", "22222222222");
Log.e("ENTER-methFirst1", "" + list3);
// Log.e("sub_sub_Obj-methFirst1", "" + sub_sub_Obj);
list1.clear();
try {
// for (int i = 0; i < list1.size(); i++) {
// if (list3 == list1.get(i)) {
if (list3 == mainObj.keys().toString()) {
Log.e("<<<matched", "yesssss");
} else {
Log.e("waste of time>>>>", "do");
}
subArray = sub_sub_Obj.getJSONArray(list3);
Log.e("size>>>>>>>>>>>", "" + subArray.length());
for (int j = 0; j < subArray.length(); j++) {
Log.i("Test----->>>>>>", "test--" + j);
JSONObject Obj = subArray.getJSONObject(j);
getObjMeth(Obj);
//break;
}
// }
// }
} catch (Exception e) {
}
}
`
pls help me
If you want to iterate over the JSONArray you can do it with a for loop:
for (int i = 0; i < myArray.length; i++) {
JSONObject myObject = (JSONObject) myArray.get(i);
String myString = myObject.getString("myString");
}
Hi I am using volley jar in my android app to cache the json data for the offline mode.It works perfectly.Here is my code
Cache cache1 = AppController.getInstance().getRequestQueue().getCache();
Entry entry1 = cache1.get(URL);
if (entry1 != null) {
// fetch the data from cache
try {
data2 = new String(entry1.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data2));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
AppController.getInstance().getRequestQueue().getCache().remove(URL);
// making fresh volley request and getting json
JsonObjectRequest jsonReq1 = new JsonObjectRequest(Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error:" + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq1);
}
private void parseJsonFeed(JSONObject response) {
try {
feedArray = response.getJSONArray("events");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
event_id.add(feedObj.getInt("event_id"));
event_desc.add(feedObj.getString("event_title"));
event_date.add(feedObj.getString("event_date"));
event_place.add(feedObj.getString("event_place"));
event_time.add(feedObj.getString("event_time"));
}
listView.setAdapter(new dataListAdapter(event_date,event_desc,event_place,event_time));
//Log.i("event1111", event.toString());
// Log.i("event2222", event2.toString());
Toast.makeText(getActivity(), "dataa"+event_id, 5000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
my problem is that I got data.But When I updated json data,the cache data will not update.So how can I change cache data based on json data.Please help me thanks in advance :)
Set the cache header response of your server correctly, I think you need to change the max-age of the header or any custom configuration because Volley looks at the header then stores the response in the cache, here is how it dose:
headerValue = headers.get("Cache-Control");
if (headerValue != null) {
hasCacheControl = true;
String[] tokens = headerValue.split(",");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("no-cache") || token.equals("no-store")) {
return null;
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
}
} else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
maxAge = 0;
}
}
}
headerValue = headers.get("Expires");
if (headerValue != null) {
serverExpires = parseDateAsEpoch(headerValue);
}
serverEtag = headers.get("ETag");
// Cache-Control takes precedence over an Expires header, even if both exist and Expires
// is more restrictive.
if (hasCacheControl) {
softExpire = now + maxAge * 1000;
} else if (serverDate > 0 && serverExpires >= serverDate) {
// Default semantic for Expire header in HTTP specification is softExpire.
softExpire = now + (serverExpires - serverDate);
}
Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = entry.softTtl;
entry.serverDate = serverDate;
entry.responseHeaders = headers;
I'm having android Button for Login.
below is the onclick listener of that button.
btnLoginFB.setOnClickListener(new View.OnClickListener() {
#
Override
public void onClick(View v) {
Session s = new Session(Startup.this);
Session.setActiveSession(s);
Session.OpenRequest request = new Session.OpenRequest(Startup.this);
List < String > permissions = new ArrayList < String > ();
permissions.add("friends_birthday");
permissions.add("friends_location");
request.setPermissions(permissions);
request.setCallback(new Session.StatusCallback() {
#
Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.newMyFriendsRequest(Session.getActiveSession(), new Request.GraphUserListCallback() {
#
Override
public void onCompleted(List < GraphUser > users, Response response) {
if (users != null) {
for (int i = 0; i < users.size(); i++) {
String frndLoc = "empty";
try {
users.get(i).getLocation().getProperty("name");
frndLoc = "" + users.get(i).getLocation().getProperty("name");
} catch (Exception e) {}
Toast.makeText(Startup.this, users.get(i).getBirthday() + " - " +
users.get(i).getName() + "\n" +
frndLoc, Toast.LENGTH_LONG).show();
}
}
}
}).executeAsync();
} // end of if (session.isOpened())
} // end of call
});
s.openForRead(request);
}
});
The problem is I'm getting null for both B'day and Location of friend.
Request friendRequest = Request.newMyFriendsRequest(activeSession, new GraphUserListCallback() {
#Override
public void onCompleted(final List<GraphUser> users, Response response) {
ArrayList<String> o = new ArrayList<String>();
for (GraphUser u : users) {
o.add(u.getInnerJSONObject().toString());
}
getSherlockActivity().startService(
new Intent(getSherlockActivity(), InsertInDBService.class).putExtra("fbdata", o));
}
}
});
Parse the reponse
int count = users.size();
for (int i = 0; i < count; i++) {
String name = "", id = "", photoUrl = "";
String birthday = "", location = "";
String website = "";
JSONObject o = null;
try {
o = new JSONObject(users.get(i));
} catch (JSONException e) {
}
try {
id = o.getString("id");
name = o.getString("name");
photoUrl = o.getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
dbFacebookMain.deleteFACEBOOK();
}
try {
location = o.getJSONObject("location").getString("name");
} catch (JSONException e) {
}
try {
birthday = o.getString("birthday");
} catch (JSONException e) {
}
try {
website = o.getString("website");
} catch (JSONException e) {
}
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonArray = jsonObj.getJSONObject("query").getJSONObject("results").getJSONArray("row");
int arrayCount = jsonArray.length();
for(int i=0; i < arrayCount; i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
String col0 = jsonData.getString("col0");
String col1 = jsonData.getString("col1");
// etc, etc ...
// put those values in arrays or whatever here.
}
What is the syntax for the same operation but using the 'Jackson' parsing libary?
I currently have:
JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createParser(res);
JsonToken current;
current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();
if (fieldName.equals("row")) {
if (current == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
JsonNode node = jp.readValueAsTree();
Log.e("KFF", node.get("col0").asText());
}
} else {
Log.e("KFF", "Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
Log.e("KFF", "Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Example of the data i need to parse:
http://pastebin.com/rhD2d9fx