Issue with a for loop over JSON - java

I seem to be having an issue looping through a JSONObject
The following loop is within a try catch. I am trying to loop through returned JSON, but it skips
try {
JSONObject jsonObject = new JSONObject(result);
// Extract data from json and store into ArrayList as class objects
for(int i = 0; i < jsonObject.length(); i++){
JSONObject jD = jsonObject.getJSONObject(i).;
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}
Response JSON
{"count": 30, "recipes": [{"publisher": "Closet Cooking", "f2f_url": "http://food2fork.com/view/35382", "title": "Jalapeno Popper Grilled Cheese Sandwich", "source_url": "http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html", "recipe_id": "35382", "image_url": "http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg", "social_rank": 100.0, "publisher_url": "http://closetcooking.com"}, {"publisher": "The Pioneer Woman",
Code within the onPostExecute.
even with the changes still ignores the inners and moves straight to the catch.
#Override
protected void onPostExecute(String result) {
List<DataRecipes> data = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArrayRecipe = jsonObject.getJSONArray("recipes");
for(int i = 0; i < jsonArrayRecipe.length(); i++){
JSONObject jD = jsonArrayRecipe.getJSONObject(i);
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}
// Setup and Handover data to recyclerview
mRVRecipePrice = findViewById(R.id.jsonText);
mAdapter = new AdapterRecipe(Main_Food.this, data);
mRVRecipePrice.setAdapter(mAdapter);
mRVRecipePrice.setLayoutManager(new LinearLayoutManager(Main_Food.this));
}

You need to access the recipe array first
Try this
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArrayrecipe = jsonObject .getJSONArray("recipes");
for(int i = 0; i < jsonArrayrecipe .length(); i++){
JSONObject jD = jsonArrayrecipe .getJSONObject(i);
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}

Related

How to save this JSON Object to Array List in Android

I'm having troubles finding a way how to parse this JSONObject on Java:
{"market_cap":[[1518987267000,183700781183],
[1518987567000,183687424480],
[1518987868000,183687424480],
.
.
.
[1519080954726,7730730000]]}
This is the full json: JSON
I´m looking for save these data on a List Array...
I have updated my full function:
static String urlJsonArry2 = "http://coincap.io/history/1day/BTC";
private JSONObject responseJsonObject;
private void GettingDataGraph(){
progressDialog.setMessage("Getting Data");
progressDialog.show();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry2,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
ArrayList<Object> MARKET_CAP_ARRAY_LIST = new ArrayList<>();
JSONArray marketCapArray = responseJsonObject.optJSONArray("volume");
for (int i=0; i< marketCapArray.length(); i++){
JSONArray array1 = (JSONArray) marketCapArray.get(i);
for (int j=0; j < array1.length(); j++){
MARKET_CAP_ARRAY_LIST.add(array1.get(j));
}
}
Log.d(TAG, String.valueOf(MARKET_CAP_ARRAY_LIST));
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "ERROR " + e.getMessage());
progressDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d(TAG, "ERROR " + error.getMessage());
progressDialog.dismiss();
}
});
AppController.getInstance().addToRequestQueue(req);
}
My updated logcat is this:
D/Volley: [1] 5.onErrorResponse: ListMain
D/ListMain: ERROR org.json.JSONException: Value {"volume":[[1518987267000,9151900000],[1518987567000,9157160000],[1518987868000,9169080000],[1518988166000,9161370000],[1518988467000,9154150000],[1518988765000,9144130000],[1518989067000,9128060000],[1518989366000,9117040000],[1518989665000,9113130000],[1518989965000,9094710000],[1518990267000,9110340000],[1518990567000,9144620000],[1518990868000,9168270000],[1518991167000,9179440000],[1518991467000,9181180000],[1518991767000,9175010000],[1518992067000,9175640000],[1518992366000,9161110000],[1518992667000,9140220000],[1518992966000,9146430000],[1518993266000,9164780000],[1518993567000,9136680000],[1518993866000,9087550000],[1518994167000,9035050000],[1518994466000,8991310000],[1518994766000,8990680000],[1518995067000,8973400000],[1518995367000,8941170000],[1518995667000,8895200000],[1518995966000,8853810000],[1518996267000,8821540000],[1518996566000,8778680000],[1518996867000,8778560000],[1518997167000,8802030000],[1518997467000,8808330000],[1518997767000,8793550000],[1518998068000,8778190000],[1518998367000,8744010000],[1518998667000,8730850000],[1518998967000,8739700000],[1518999266000,8708270000],[1518999566000,8692760000],[1518999867000,8696210000],[1519000167000,8691320000],[1519000467000,8704830000],[1519000768000,8701960000],[1519001067000,8703500000],[1519001366000,8690490000],[1519001666000,8654650000],[1519001966000,8645390000],[1519002266000,8642730000],[1519002567000,8594570000],[1519002867000,8634390000],[1519003166000,8671810000],[1519003466000,8673840000],[1519003769000,8680670000],[1519004068000,8676080000],[1519004369000,8672160000],[1519004666000,8635240000],[1519004969000,8601340000],[1519005266000,8610940000],[1519005567000,8609810000],[1519005869000,8623850000],[1519006173000,8627350000],[1519006467000,8593110000],[1519006765000,8582360000],[1519007066000,8558920000],[1519007367000,8520250000],[1519007666000,8534120000],[1519007969000,8565770000],[1519008268000,8568240000],[1519008568000,8568010000],[1519008867000,8551680000],[1519009168000,8520880000],[1519009467000,8505580000],[1519009769000,8499980000],[1519010069000,8460400000],[1519010368000,8443030000],[1519010667000,8435930000],[1519010969000,8385870000],[1519011267000,8336820000],[1519011567000,8314420000],[1519011866000,8306510000],[1519012167000,8289780000],[1519012467000,8265550000],[1519012767000,8230840000],[1519013067000,8198170000],[1519013368000,8184000000],[1519013668000,8183500000],[1519013967000,8177700000],[1519014268000,8173580000],[1519014567000,8169000000],[1519014868000,8156480000],[1519015166000,8142310000],[1519015466000,8135780000],[1519015767000,8146410000],[1519016067000,8142550000],[1519016368000,8121680000],[1519016668000,8100770000],[1519016967000,8107950000],[1519017268000,8058870000],[1519017566000,7990860000],[1519017867000,7953970000],[1519018169000,7918280000],[1519018467000,7881990000],[1519018768000,7823290000],[1519019067000,7815010000],[1519019366000,7808360000],[1519019667000,7784880000],[1519019968000,7749460000],[1519020267000,7735900000],[1519020566000,7734530000],[1519020865000,7718370000],[1519021166000,7699210000],[1519021467000,7685120000],[1519021767000,7677750000],[1519022067000,7660540000],[1519022365000,7627040000],[1519022666000,7621670000],[1519022966000,7620360000],[1519023267000,7613420000],[1519023568000,7583250000],[1519023867000,7563660000],[1519024167000,7581690000],[1519024467000,7592450000],[1519024767000,7575950000],[1519025068000,7623950000],[1519025368000,7705190000],[1519025666000,7750020000],[1519025967000,7794050000],[1519026267000,7820790000],[1519026567000,7814480000],[1519026868000,7819060000],[1519027167000,7811230000],[1519027467000,7812310000],[1519027766000,7806300000],[1519028069000,7717960000],[1519028367000,7717970000],[1519028666000,7739410000],[1519028967000,7770270000],[1519029267000,7787760000],[1519029567000,7778010000],[1519029867000,7753830000],[1519030166000,7743590000],[1519030467000,7744180000],[1519030767000,7712770000],[1519031066000,7684790000],[1519031367000,7648400000],[1519031667000,7630540
I'm getting a onErrorResponse
In case someone is interested...this code works good for this array:
ArrayList<Object> MARKET_CAP_ARRAY_LIST = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("market_cap");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray array1 = (JSONArray) jsonArray.get(i);
for (int j=0; j < array1.length(); j++){
MARKET_CAP_ARRAY_LIST.add(array1.get(j));
Log.d("ARRAY: ", String.valueOf(MARKET_CAP_ARRAY_LIST));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Thanks...
You can parse JSON like this.
private void parseJsonObject(JSONObject responseJsonObject) throws JSONException {
ArrayList<Object> MARKET_CAP_ARRAY_LIST = new ArrayList<>();
JSONArray marketCapArray = responseJsonObject.optJSONArray("market_cap");
for (int i=0; i< marketCapArray.length(); i++){
JSONArray array1 = (JSONArray) marketCapArray.get(i);
for (int j=0; j < array1.length(); j++){
MARKET_CAP_ARRAY_LIST.add(array1.get(j));
}
}
}
private class JsonAsyncTask extends AsyncTask<Void, Void, Void> {
String url ;
public JsonAsyncTask(String url) {
this.url = url;
}
#Override
protected Void doInBackground(Void... voids) {
processApiResponse(url);
return null;
}
private void processApiResponse(String url) {
try {
URL jsonUrl = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(jsonUrl.openStream()));
String inputLine;
StringBuilder jsonStringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
jsonStringBuilder.append(inputLine);
in.close();
String jsonString = jsonStringBuilder.toString();
Volume volume = new Gson().fromJson(jsonString, Volume.class);
System.out.println(volume);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The POJO classes
private class Volume {
ArrayList<VolumeObject> market_cap;
ArrayList<VolumeObject> volume;
}
private class VolumeObject extends ArrayList<Double> {
}
You can use
// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
to add Gson in your project.
And to call the AsyncTask in an activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
JsonAsyncTask task = new JsonAsyncTask("http://coincap.io/history/1day/BTC");
task.execute();
}
I hope this helps
Note: For the network operation you can use any other library. Whereas retrofit is preferred by me.

i got error about java.lang.String cannot be converted to JSONarray

In my code, I am trying to populate value spinner from a MySQL database, but I can't get the value.
What's wrong on my jsonArray?
java.lang.String cannot be converted to JSONObject
JsonArrayRequest jsonSpinnerObjectRequest = new JsonArrayRequest(fetch_city_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject = null;
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject city = jsonArray.getJSONObject(i);
Log.i("onResponseSpinner", city.getString("kd_kelas") + " " + city.getString("kelas"));
kelasList.add(city.getString("kelas"));
}
spinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR in response"+error.getMessage());
}
});
Here you set a JSON object to null then try to get JSON Array from it:
JSONObject jsonObject = null;
JSONArray jsonArray = jsonObject.getJSONArray("result");
I think you are wanting something like this:
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray = jsonArray = new jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject city = jsonArray.getJSONObject(i);
Log.i("onResponseSpinner", city.getString("kd_kelas") + " " + city.getString("kelas"));
kelasList.add(city.getString("kelas"));
}
spinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
Looking at your code, i think you are already getting the JSON array in response so just get the values from this JSON array only, please go through the following code
JsonArrayRequest jsonSpinnerObjectRequest = new JsonArrayRequest(fetch_city_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject city = response.getJSONObject(i);
Log.i("onResponseSpinner", city.getString("kd_kelas") + " " + city.getString("kelas"));
kelasList.add(city.getString("kelas"));
}
spinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR in response"+error.getMessage());
}
});

How extract JSONObject from JSONArray in android

I want to read only the "value" object from this jsonarray
"body":{"und":[{"value":"hi friends!!!","summary":null,"format":null}]}
This is my code:
protected void onPostExecute(final JSONObject result) {
try {
TextView lst2 = (TextView) findViewById(R.id.View2);
JSONArray cast = result.getJSONArray("body");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("value");
lst2.setText(name);
}
} catch (Exception e2) {
Log.v("Error adding article", e2.getMessage());
}
}
JSONObject result is the response from the rest server.
body is not array its object, you need to get und out of body as JSONArray first
protected void onPostExecute(final JSONObject result) {
try {
TextView lst2 = (TextView) findViewById(R.id.View2);
JSONArray cast = result.getJSONObject("body").getJSONArray("und");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("value");
lst2.setText(name);
}
} catch (Exception e2) {
Log.v("Error adding article", e2.getMessage());
}
}
Hope it helps

Web-Services Android Java

now i have a button called activities that when u press on it it gets from database activity name and which class in school did this activity and the images of this activity so am doing something like in server side java part am getting all activites of class a in an arraylist and of class b in an arraylist and class c in an arraylist then i added these 3 arraylists in an arraylist!..and this big arraylist i converted to json but when i receive it in android part there is an error :(
Server side:
public static String constructJS(String tag, boolean status,ArrayList<ArrayList<Activities>> f) {
JSONObject obj = new JSONObject();
try {
for(int i=0;i<f.size();i++){
obj.put("tag", tag);
obj.put("status", new Boolean(status));
String json = new Gson().toJson(f);
obj.put("data",json);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
}
return obj.toString();
}
and here when i print the obj.toString i get the json!!
in android part when i receive it :
Client Side
public void onSuccess(String response) {
// Hide Progress Dialog
// prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(response);
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
String j = obj.get("data").toString();
Toast.makeText(getApplicationContext(), j, Toast.LENGTH_LONG).show();
JSONArray data = new JSONArray(j);
Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < data.length(); i++) {
JSONObject busName = data.getJSONObject(i);
String busPhone = busName.getString("activityname");
String busPhon = busName.getString("activityclass");
Toast.makeText(getApplicationContext(), busPhon, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
i get the error when i debug in this line : JSONArray data = new JSONArray(j);
there is no need to create object of jsonarray
i.e. JSONArray data = new JSONArray(j);
just assign the jsonarray value to JSONArray reference
public void onSuccess(String response) {
// Hide Progress Dialog
// prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(response);
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
//String j = obj.get("data").toString();
// dont't need to do this
Toast.makeText(getApplicationContext(), j, Toast.LENGTH_LONG).show();
//JSONArray data = new JSONArray(j);
JSONArray data = obj.getJSONArray("data"); //add this line
Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < data.length(); i++) {
JSONObject busName = data.getJSONObject(i);
String busPhone = busName.getString("activityname");
String busPhon = busName.getString("activityclass");
Toast.makeText(getApplicationContext(), busPhon, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}

Json to hashMap listview

I'm new to android development. Can you please help me to put my code to the hashmap-listview? Here I am loading bank images to the ListView. in my new JSON there is a key and value. ie (BankName , logo)
public void ListDrwaer() {
List<String> listImg = new ArrayList<String>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
listImg.add(test1);
Log.d("URL", test1);
}
ItemsAdapter adapter = new ItemsAdapter(getActivity(), listImg);
menu.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
}
You can use Pairs instead of HashMap
Try this
public void ListDrwaer() {
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
String BankName = jsonChildNode.optString("id");
listData.add(new Pair<String,String>(BankName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
}

Categories