I'm trying to get the item name, brand name and total carbohydrate value out of the following JSON Array but am having problems with accessing the the individual values within the "fields" section. Anyone with any pointers to retrieve this info?
{
"total_hits": 49127,
"max_score": 11.919899,
"hits": [
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000022",
"_score": 11.919899,
"fields": {
"item_id": "513fceb375b8dbbc21000022",
"item_name": "Cheese, cheddar - 1 cup, diced",
"brand_name": "USDA",
"nf_total_carbohydrate": 4.08,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
},
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000021",
"_score": 11.788424,
"fields": {
"item_id": "513fceb375b8dbbc21000021",
"item_name": "Cheese, cheddar - 1 cup, melted",
"brand_name": "USDA",
"nf_total_carbohydrate": 7.54,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
/* sorry for some reason i can't get the formatting right but the "hits" is a parent of the whole highlighted code section*/
Try this:
try {
JSONObject object = new JSONObject(json);
JSONArray hits = object.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject fields = hits.getJSONObject(i).getJSONObject("fields");
String itemName = fields.getString("item_name");
String brandName = fields.getString("brand_name");
double carbohydrate = fields.getDouble("nf_total_carbohydrate");
Log.d("HitTag", itemName+" "+brandName+" "+carbohydrate);
}
} catch (JSONException e) {
e.printStackTrace();
}
I assume that you have this json:
{
"total_hits": 49127,
"max_score": 11.919899,
"hits": [
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000022",
"_score": 11.919899,
"fields": {
"item_id": "513fceb375b8dbbc21000022",
"item_name": "Cheese, cheddar - 1 cup, diced",
"brand_name": "USDA",
"nf_total_carbohydrate": 4.08,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
},
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000021",
"_score": 11.788424,
"fields": {
"item_id": "513fceb375b8dbbc21000021",
"item_name": "Cheese, cheddar - 1 cup, melted",
"brand_name": "USDA",
"nf_total_carbohydrate": 7.54,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
}
]
}
Here is the fully working code. Try this:
// Your JSON string
String jsonStr = "{\n" +
" \"total_hits\": 49127,\n" +
" \"max_score\": 11.919899,\n" +
" \"hits\": [\n" +
" {\n" +
" \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
" \"_type\": \"item\",\n" +
" \"_id\": \"513fceb375b8dbbc21000022\",\n" +
" \"_score\": 11.919899,\n" +
" \"fields\": {\n" +
" \"item_id\": \"513fceb375b8dbbc21000022\",\n" +
" \"item_name\": \"Cheese, cheddar - 1 cup, diced\",\n" +
" \"brand_name\": \"USDA\",\n" +
" \"nf_total_carbohydrate\": 4.08,\n" +
" \"nf_serving_size_qty\": 1,\n" +
" \"nf_serving_size_unit\": \"serving\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
" \"_type\": \"item\",\n" +
" \"_id\": \"513fceb375b8dbbc21000021\",\n" +
" \"_score\": 11.788424,\n" +
" \"fields\": {\n" +
" \"item_id\": \"513fceb375b8dbbc21000021\",\n" +
" \"item_name\": \"Cheese, cheddar - 1 cup, melted\",\n" +
" \"brand_name\": \"USDA\",\n" +
" \"nf_total_carbohydrate\": 7.54,\n" +
" \"nf_serving_size_qty\": 1,\n" +
" \"nf_serving_size_unit\": \"serving\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArrayHits = jsonObject.getJSONArray("hits");
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArrayHits.length(); i++)
{
JSONObject jsonObjectFields = jsonArrayHits.getJSONObject(i).getJSONObject("fields");
String itemName = null, brandName = null;
double totalCarbohydrate = 0.0;
// Item name
if (jsonObjectFields.has("item_name") && !jsonObjectFields.isNull("item_name")) {
itemName = jsonObjectFields.getString("item_name");
}
// Brand name
if (jsonObjectFields.has("brand_name") && !jsonObjectFields.isNull("brand_name")) {
brandName = jsonObjectFields.getString("brand_name");
}
// Total carbohydrate
if (jsonObjectFields.has("nf_total_carbohydrate") && !jsonObjectFields.isNull("nf_total_carbohydrate")) {
totalCarbohydrate = jsonObjectFields.getDouble("nf_total_carbohydrate");
}
Log.d("SUCCESS", "JSON Object: " + "\nItem Name: " + itemName
+ "\nBrand Name: " + brandName
+ "\nTotal carbohydrate: " + totalCarbohydrate);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT LOG:
D/SUCCESS: JSON Object:
Item Name: Cheese, cheddar - 1 cup, diced
Brand Name: USDA
Total carbohydrate: 4.08
D/SUCCESS: JSON Object:
Item Name: Cheese, cheddar - 1 cup, melted
Brand Name: USDA
Total carbohydrate: 7.54
Hope this will help~
Related
This question already has answers here:
How to iterate over a JSONObject?
(15 answers)
Closed 5 years ago.
I am creating an app in which i need to parse a list of contacts which is in JSONObject format, with key before each object, i don't know how to parse this format.
{
"1": {
"mobileContact": "98562325",
"systemContact": "9198562325"
},
"3": {
"mobileContact": "987563656",
"systemContact": "91987563656"
},
"4": {
"mobileContact": "965632525",
"systemContact": "91965632525"
},
"6": {
"mobileContact": "965436222",
"systemContact": "91965436222"
}
}
Use the keys() iterator to iterate over all the properties, and call get() for each.
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
try{
JSONObject json = new JSONObject(jsonRespondeString);
Iterator<String> iterator = json.keys();
while (iterator.hasNext()){
String key = iterator.next();
JSONObject object = json.getJSONObject(key);
String value1 = object.getString("key1");
String value2 = object.getString("key2");
}
}
catch (JSONException e){
e.printStackTrace();
}
please try this it helps
You can use GSON library to parse it.
String data = "{\n" +
" \"1\": {\n" +
" \"mobileContact\": \"98562325\",\n" +
" \"systemContact\": \"9198562325\"\n" +
" },\n" +
" \"3\": {\n" +
" \"mobileContact\": \"987563656\",\n" +
" \"systemContact\": \"91987563656\"\n" +
" },\n" +
" \"4\": {\n" +
" \"mobileContact\": \"965632525\",\n" +
" \"systemContact\": \"91965632525\"\n" +
" },\n" +
" \"6\": {\n" +
" \"mobileContact\": \"965436222\",\n" +
" \"systemContact\": \"91965436222\"\n" +
" }\n" +
"}";
Map<String, Item> itemMap = new HashMap<>();
itemMap = new Gson().fromJson(data, itemMap.getClass());
Log.i("data", itemMap);
Item Class
private class Item {
String mobileContact;
String systemContact;
// getters and setters
public String getMobileContact() {
return mobileContact;
}
public void setMobileContact(String mobileContact) {
this.mobileContact = mobileContact;
}
public String getSystemContact() {
return systemContact;
}
public void setSystemContact(String systemContact) {
this.systemContact = systemContact;
}
}
You need to add the following to the build.gradle file,
compile 'com.google.code.gson:gson:2.8.0'
My JSON:
{
"response_code": 200,
"error": false,
"train_name": "KCG YPR EXP",
"train_num": "17603",
"pnr": "1234567890",
"failure_rate": 19.346153846153847,
"doj": "20-8-2015",
"chart_prepared": "Y",
"class": "SL",
"total_passengers": 2,
"train_start_date": {
"month": 8,
"year": 2015,
"day": 20
},
"from_station": {
"code": "KCG",
"name": "KACHEGUDA"
},
"boarding_point": {
"code": "KCG",
"name": "KACHEGUDA"
},
"to_station": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"reservation_upto": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"passengers": [
{
"no": 1,
"booking_status": "S7,58,GN",
"current_status": "S7,58",
"coach_position": 9
},
{
"no": 2,
"booking_status": "S7,59,GN",
"current_status": "S7,59",
"coach_position": 9
}
]
}
What I did so far:
if(jsonStr!=null)
{
try
{
JSONObject object=new JSONObject(jsonStr);
JSONArray jsonArray=object.getJSONArray("passengers");
for (int i=0;i<=jsonArray.length();i++)
{
JSONObject o=jsonArray.getJSONObject(i);
int no= Integer.parseInt(o.optString("no").toString());
String booking_status=o.getString("Booking Status");
String current_status=o.getString("Current Status");
String coach_position=o.getString("Coach Position");
JSONObject data=o.getJSONObject("details");
String train_name = data.getString("Train Name");
int train_num = Integer.parseInt(data.optString("train number").toString());
int pnr = Integer.parseInt(data.optString("pnr").toString());
String chart_prepared = data.getString("Chart Prepared");
int total_passengers=Integer.parseInt(data.optString("total passengers").toString());
JSONObject date=data.getJSONObject("tarin_start_date");
int month=Integer.parseInt(data.optString("month").toString());
int year=Integer.parseInt(data.optString("year").toString());
int day=Integer.parseInt(data.optString("day").toString());
JSONObject co=date.getJSONObject("from_station");
String code=co.getString("code");
String name=co.getString("name");
JSONObject co1=co.getJSONObject("boarding_point");
String code1=co1.getString("code");
String name1=co1.getString("name");
JSONObject co2=co1.getJSONObject("to_station");
String code2=co2.getString("code");
String name2=co2.getString("name");
JSONObject co3=co2.getJSONObject("from_station");
String code3=co3.getString("code");
String name3=co3.getString("name");
HashMap<String,String> dtail=new HashMap<>();
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus",booking_status);
dtail.put("Current Staus",current_status);
dtail.put("Coach Positon",coach_position);
dtail.put("Train Name",train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared",chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code",code);
dtail.put("name",name);
dtail.put("code",code1);
dtail.put("name",name1);
dtail.put("code",code2);
dtail.put("name",name2);
dtail.put("code",code3);
dtail.put("name",name3);
dataList.add(dtail);
}
}
catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
else
{
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Here is your solution.
Hope this will help you. Whenever you work with JSON check all key name. It should always same as response key name
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
HashMap<String, String> dtail = new HashMap<>();
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
int no = Integer.parseInt(o.optString("no").toString());
String booking_status = o.getString("booking_status");
String current_status = o.getString("current_status");
String coach_position = o.getString("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus", booking_status);
dtail.put("Current Staus", current_status);
dtail.put("Coach Positon", coach_position);
}
String train_name = object.getString("train_name");
int train_num = Integer.parseInt(object.optString("train_num").toString());
int pnr = Integer.parseInt(object.optString("pnr").toString());
String chart_prepared = object.getString("chart_prepared");
int total_passengers = Integer.parseInt(object.optString("total_passengers").toString());
JSONObject date = object.getJSONObject("train_start_date");
int month = Integer.parseInt(date.optString("month").toString());
int year = Integer.parseInt(date.optString("year").toString());
int day = Integer.parseInt(date.optString("day").toString());
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("reservation_upto");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
dtail.put("Train Name", train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared", chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
dataList.add(dtail);
} catch (final JSONException e) {
Log.e("Json", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
Hope this will help :-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy);
String str = "{\n" +
" \"response_code\": 200,\n" +
" \"error\": false,\n" +
" \"train_name\": \"KCG YPR EXP\",\n" +
" \"train_num\": \"17603\",\n" +
" \"pnr\": \"1234567890\",\n" +
" \"failure_rate\": 19.346153846153847,\n" +
" \"doj\": \"20-8-2015\",\n" +
" \"chart_prepared\": \"Y\",\n" +
" \"class\": \"SL\",\n" +
" \"total_passengers\": 2,\n" +
" \"train_start_date\": {\n" +
" \"month\": 8,\n" +
" \"year\": 2015,\n" +
" \"day\": 20\n" +
" },\n" +
" \"from_station\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"boarding_point\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"to_station\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"reservation_upto\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"passengers\": [\n" +
" {\n" +
" \"no\": 1,\n" +
" \"booking_status\": \"S7,58,GN\",\n" +
" \"current_status\": \"S7,58\",\n" +
" \"coach_position\": 9\n" +
" },\n" +
" {\n" +
" \"no\": 2,\n" +
" \"booking_status\": \"S7,59,GN\",\n" +
" \"current_status\": \"S7,59\",\n" +
" \"coach_position\": 9\n" +
" }\n" +
" ]\n" +
"}";
parseJson(str);
}
private void parseJson(String jsonStr) {
HashMap<String, String> dtail = new HashMap<>();
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
int responseCode = object.getInt("response_code");
boolean error = object.getBoolean("error");
String train_name = object.getString("train_name");
int train_num = object.getInt("train_num");
int pnr = object.getInt("pnr");
double failurerate = object.getDouble("failure_rate");
String dateofJoin = object.getString("doj");
String chart = object.getString("chart_prepared");
String Class = object.getString("class");
int total_passengers = object.getInt("total_passengers");
JSONObject date = object.getJSONObject("train_start_date");
int month = date.getInt("month");
int year = date.getInt("year");
int day = date.getInt("day");
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("from_station");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int no = jsonObject.getInt("no");
String booking_status = jsonObject.getString("booking_status");
String current_status = jsonObject.getString("current_status");
int coach_position = jsonObject.getInt("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("booking_status", booking_status);
dtail.put("current_status", current_status);
dtail.put("coach_position", String.valueOf(coach_position));
}
dtail.put("responseCode", String.valueOf(responseCode));
dtail.put("error", "" + error);
dtail.put("Train Name", train_name);
dtail.put("dateofJoin", dateofJoin);
dtail.put("chart", chart);
dtail.put("Class", Class);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("FAILURE_RATE", String.valueOf(failurerate));
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
Log.e("Result------", "" + dtail);
} catch (final JSONException e) {
Log.e("tag", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Need Help
I have Json through which i have to retrieve objects but unable to retrieve.
I have used multiple objects also to retrieve but no success.
JSON:
{
"status": 1,
"data": [{
"restaurent_id": "1",
"user_id": "6",
"zone_id": "1",
"restaurentAddress": {
"restaurent_address_id": "1"
},
"restaurentInfo": {
"restaurent_info_id": "1",
"restaurent_bussiness_owner_name": "Vijay"
},
"restaurentSetting": {
"restaurent_setting_id": "1",
"minimum_purcase": "200",
"payment_method_id": "1",
"title": "Best Hotel"
},
"zone": {
"zone_id": "1",
"by_zipcode": "1"
}
}]
}
and i want to fetch restaurentAddress and restaurentInfo
MY mainActivity.java file
package com.example.premi.jsonlist;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="{\n" +
"\t\"status\": 1,\n" +
"\t\"data\": [{\n" +
"\t\t\"restaurent_id\": \"1\",\n" +
"\t\t\"user_id\": \"6\",\n" +
"\t\t\"zone_id\": \"1\",\n" +
"\t\t\"restaurentAddress\": {\n" +
"\t\t\t\"restaurent_address_id\": \"1\"\n" +
"\t\t},\n" +
"\t\t\"restaurentInfo\": {\n" +
"\t\t\t\"restaurent_info_id\": \"1\",\n" +
"\t\t\t\"restaurent_bussiness_owner_name\": \"Vijay\"\n" +
"\t\t},\n" +
"\t\t\"restaurentSetting\": {\n" +
"\t\t\t\"restaurent_setting_id\": \"1\",\n" +
"\t\t\t\"minimum_purcase\": \"200\",\n" +
"\t\t\t\"payment_method_id\": \"1\",\n" +
"\t\t\t\"title\": \"Best Hotel\"\n" +
"\t\t},\n" +
"\t\t\"zone\": {\n" +
"\t\t\t\"zone_id\": \"1\",\n" +
"\t\t\t\"by_zipcode\": \"1\"\n" +
"\t\t}\n" +
"\n" +
"\t}]\n" +
"}";
String dataoutput = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONObject status = jsonRootObject.optJSONObject("status");
JSONArray Dataarray =status.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < Dataarray.length(); i++){
JSONObject jsonObject = Dataarray.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentAddress");
for(int j = 0 ; j < Data.length(); j++){
JSONObject GetData =Data.getJSONObject(String.valueOf(j));
int id = Integer.parseInt(GetData.getString("restaurent_address_id"));
String postcode = GetData.getString("postcode");
String addresss = GetData.getString("restaurent_address");
dataoutput += " : \n id= "+ id +" \n postcode= "+ postcode +" \n address= "+ addresss +" \n ";
}}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
}
Try this out:
try {
JSONObject object = (JSONObject) new JSONTokener(YOUR_JSON_STRING).nextValue();
String restaurentAddressId = object.getJSONArray("data").getJSONObject(0).getJSONObject("restaurentAddress").getString("restaurent_address_id");
String restaurentInfoId = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_info_id");
String restaurentBizOwnerName = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_business_owner_name");
}
catch (JSONException e) {
}
Its Done I tried this
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray mainnode =jsonRootObject.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < mainnode.length(); i++){
JSONObject jsonObject = mainnode.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentInfo");
int id = Integer.parseInt(Data.getString("restaurent_info_id"));
String postcode = Data.getString("restaurent_phone_number");
String addresss = Data.getString("restaurent_bussiness_owner_name");
dataoutput += " : \n restaurent_id= "+ id +" \n restaurent_info_id= "+ postcode +" \n restaurent_address_id= "+ addresss +" \n ";
}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
I just removed Status Object
and another for loop Thanks For the Help Got little Bit Help from You :)
Currently working on an Android app with CookieManager..
I am trying to do PUT requests using a for loop but for some odd reason, only the first two requests succeed. I asked the server guy for help and he indicated that the other PUT requests fail because they do not have a cookie attached.
This is the for loop that I'm using.
for(int i = 0; i < userList.size(); i++) {
User user = userList.get(i);
String url = apiURL;
String address = user.getEmail() == null ? "nil":user.getEmail();
String jsonString = "{build:\"" + String.valueOf(BuildConfig.VERSION_CODE) + "\",device_id:\"" + ((MainActivity)activity).tmDevice + "\",platform:\"android\",\n" +
" type:\"User\",\n" +
" id:\"" + String.valueOf(user.getId()) + "\",\n" +
" first_name:\"" + user.getFirstName() + "\",\n" +
" last_name:\"" + user.getLastName() + "\",\n" +
" name:\"" + user.getName() + "\",\n" +
" image:{\n" +
" type:\"UserPhoto\",\n" +
" id:\"1a035500-012f-1cc2-9d22-96a73beda35e\"\n" +
" },\n" +
" emails:[\n" +
" {\n" +
" type:\"Email\",\n" +
" address:" + address + "\n" +
" }\n" +
" ],\n" +
" phone_numbers:[]\n" +
" }";
JSONObject js = null;
try {
js = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject finalJs = js;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.PUT,url, finalJs,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("putresponse", String.valueOf(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("puterror", String.valueOf(error));
}
});
VolleySingleton.getInstance((MainActivity) activity).addToRequestQueue(jsObjRequest);
}
This is the code for setting CookieManager.
manager = new CookieManager();
CookieHandler.setDefault(manager);
Even the GET requests right before the PUT requests work fine..
Any help?
After 3 days of seaching and reading about CookieManager
I finally find and make a perfect solution :
static CookieManager myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);;
final public static void saveCookies(HttpURLConnection connection , Context context) {
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = null;
try {
cookiesHeader = headerFields.get("Set-Cookie");
} catch (Exception e) {
e.printStackTrace();
}
if (cookiesHeader != null && myCookies != null) {
for (String cookie : cookiesHeader) {
try {
cookie = cookie.replace("\"", "");
myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
String new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("cookie", new_cookie).commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
final public static void loadCookies(HttpURLConnection connection , Context context) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
}
else {
String new_cookie = PreferenceManager.getDefaultSharedPreferences(context).getString("cookie" , "");
connection.setRequestProperty("Cookie", new_cookie );
}
}
I have a database with the columns: id, pdate, pvalue1, pvalue2. First I make a query with a cursor:
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "_id","pdate","pvalue1","pvalue2"},
"pdate >= ? AND pdate <= ?", new String[] { datefrom, dateto }, null, null, null);
This gives me some rows, for example if pdate = 20120318, then pvalue1 = 58, pvalue2=29. These are strings so I can give a value of "XX" to pvalue2. I would like to sum the pvalue1 between the given datefrom and dateto and group them by pdate where pvalue2 = XX. My problem is that I cannot put this condition into the query (with that its working, like "pvalue2 = XX"..), because I need the other datas too.
if (c.moveToFirst())
{
do{
if (c.getString(3).equals("XX")){
Log.i("XX", c.getString(1) + " " + c.getString(2)) + " " + c.getString(3));
}
else {
Log.i("NotXX", c.getString(1) + " " + c.getString(2)) + " " + c.getString(3));
}
while (c.moveToNext());
}
}
It is okay so far, so I can log the datas with this where pvalue2 = XX and NotXX and get something like this:
(pdate,pvalue1,pvalue2) 20120317,48,29;------;20120317,21,54;-------20120317,11,XX;-----20120318,79,71;-------20120318,21,XX;
What I would like to do?
First: Grouping the sums (pvalue1) by pdate and indicate it if pvalue2 is XX or notXX, so somethnig like this:
20120317,NotXX,69 (since 48+21=69) -------- 20120317,XX,11 -------- 20120318,NotXX,79 -------- 20120318,XX,21
After this I would like to substract the XX sum from the NotXX sum for every day. I would like to get:
20120317,58 (since 69-11) ------- 20120318,58 (since 79-21)
How sould I do this?
Thank you very much in advance!
My problem is that I cannot put this condition into the query
You are probably wrong. You can add something like (syntax may contain errors)
"select sum(select pdate from DATABASE_TABLE where pdata > x and pdate < y) as sum"
to the projection argument and you get that result as a column named sum. The only problem is that there is no support for ? in projection (at least I have not tried it but I guess it would not work)
If that's not what you want then there is very likely a different way. SQLite is very powerful.
Edit:
Would that be what you want? It's not done in SQL but it would print the sum you want for each day.
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "_id","pdate","pvalue1","pvalue2"},
"pdate >= ? AND pdate <= ?", new String[] { datefrom, dateto }, null, null, "pdate");
boolean first = true;
if (c != null) {
String currentDate = null;
int sum = 0;
while (c.moveToNext()) {
String date = c.getString(1);
int value1 = c.getInt(2);
String value2 = c.getString(3);
if (!date.equals(currentDate)) {
if (!first) {
Log.d("TAG", "The result for " + currentDate + " is: " + sum);
} else {
Log.d("TAG", "Date has changed, but we don't have data yet.");
}
first = false;
currentDate = date;
sum = 0;
}
if ("XX".equals(value2)) {
Log.d("TAG", "new line: " + date + ", " + value1 + ", " + value2 + " -");
sum -= value1;
} else {
Log.d("TAG", "new line: " + date + ", " + value1 + ", " + value2 + " +");
sum += value1;
}
}
if (!first) {
Log.d("TAG", "The last result: " + currentDate + " is: " + sum);
}
c.close();
}
Edit2: This might work when you want it done by the database.
Cursor c = ourDatabase.rawQuery(
"SELECT pdate, sum(sum2) AS sum1 FROM " +
"(" +
" SELECT pdate, pvalue1, pvalue2, -sum(pvalue1) AS sum2 " +
" FROM " + DATABASE_TABLE +
" WHERE pvalue2='XX' GROUP BY pdate" +
" UNION " +
" SELECT pdate, pvalue1, pvalue2, sum(pvalue1) AS sum2 " +
" FROM " + DATABASE_TABLE +
" WHERE pvalue2!='XX' GROUP BY pdate" +
") " +
" WHERE pdate>=? AND pdate<=? " +
" GROUP BY pdate",
new String[] { datefrom, dateto });
if (c != null) {
while (c.moveToNext()) {
String date = c.getString(0);
int value1 = c.getInt(1);
Log.d("TAG", "The result for " + date + " is: " + value1);
}
c.close();
}