How to Get Particular Values From Volley JSON Response Data Using Android? - android

I have successfully Integrated Volley library into my android studio project and got below responses. Now I need to get particular values from below response. I need to GET (A, B, C, D, E,etc,.. )values and related boys and girls values also. Once I got it I need to list out on list view like below model.
I am expecting :
-----------------------------------------
Title Boys Girls
-----------------------------------------
A 1.5 3.5
-----------------------------------------
B 1.5 3.5
-----------------------------------------
Below My Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Displays Home Screen
setContentView(R.layout.activity_list);
//displaying TextView
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "MYURL";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
txtDisplay.setText("Response => "+response.toString());
System.out.println("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
}
Below My Response :
{
   "response":{
      "A":{
         "boys":1.5,
         "girls":"3.5",
      },
      "B":{
         "boys":1.5,
         "girls":"3.5",
      },
      "E":{
         "boys":1.5,
         "girls":"3.5",
      }
  },
   "schools":{
   },
   "distances":"172 KM"
}

use following code to get values:
JsonObject json = response.get("response");
String a =json.get("A").toString();
similarly find other values;
eg;
when you get
JsonObject json = response.get("response");
then the json will be :
{
"A":{
"boys":1.5,
"girls":"3.5",
},
"B":{
"boys":1.5,
"girls":"3.5",
},
"E":{
"boys":1.5,
"girls":"3.5",
}
}
and if you want to get A / B/ C from this json use
jsonA = json.get("A");
{
"boys":1.5,
"girls":"3.5",
}
if you want to retrive boys from A
then
String boys = jsonA.get("boys").toString();
similarly
json.get("B");
and
json.get("C");

In order to get the string from the json object you can use the following
JSONObject jObj=new JSONObject(response.toString());
for boys of type a
String a = jObj.getJSONObject("response").getJSONObject("A").getString("boys").toString();
for girls of type a
String b = jObj.getJSONObject("response").getJSONObject("A").getString("girls").toString();
run the follwoing lines in a loop and store them according to your needs

I got it myself, What I am expected.
JSONObject data = response.getJSONObject("response");
Iterator keys = data.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = data.getJSONObject(currentDynamicKey);
// do something here with the value...
}

Related

Handling Volley when no key exists

I have implemented Volley and Recycler view to parse and display a list of few items from a simple JSON file.
There are at times when a key doesnot exists in an object but may appear in other object. That key is already defined using object.getInt("someKey").
As soon as Volley starts parsing the object with the missing key, it breaks out of the for loop (objects are stored in array) and catches the JSONException e, which is exactly what the app is supposed to do in case of a missing key.
However, I would like to prevent this behavior and use a placeholder value for that missing key of that particular object, so that the array list gets successfully buildup and recyclerview gets filled thereby application starts working normally.
What logic can I use in order to achieve this behavior?
Thank you!
private void parseJSON() {
String url = "https://example.com/index.json";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String title = object.getString("subject");
String description = object.getString("message");
String imageUrl = object.getString("thumb");
Integer threadId = object.getInt("threadId");
mList.add(new Item( title, description, threadId));
}
mItemAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
In the above code, threadId is the key, which may or maynot appear in many objects of the JSON.
You can check firstly if your key exists on object
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String title = object.getString("subject");
String description = object.getString("message");
String imageUrl = object.getString("thumb");
Integer threadId;
if(object.toString().contain("threadId"){
threadId = object.getInt("threadId");
}else{
threadId = 0;
}
mList.add(new Item( title, description, threadId));
}
mItemAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
If i understood well your Question , here what you need to do , if you are not sure if this key exists use the following
jsonObject.optBoolean("yourKey");
jsonObject.optInt("yourKey");
jsonObject.optString("yourKey");
jsonObject.optLong("yourKey");
jsonObject.optDouble("yourKey");
jsonObject.optJSONArray("yourKey");
this will make sure jsonObject will ignore that key if it doesn't exist.
object.getInt("someKey") is to get value from "somekey".if somekey is not appeared it shows JSONException. Instead of this object.optInt("someKey"). It will get value from "somekey" if it appears, otherwise it skipped. This is simple solution. Thanks

How to fetch a specific data from a json format string to populate recyclerview?

today I am having problem understanding how to extract specific values from this json string.
Mind you, I intend to populate a recyclerview with datas taken from here.
Let me first show you the format of the json string:
[
{
"recipe_filter":"Veg",
"recipe_array":[
{
"recipe_name":"Nimki",
"recipe_image":"nimki",
"isFavourite":false,
"isInCookList":false,
"recipe_prep_time":"2 Hours",
"recipe_prep_steps":"Steps",
"recipe_ingredients":"123456"
},
{
"recipe_name":"Palang Paneer",
"recipe_image":"palang_paneer",
"isFavourite":false,
"isInCookList":false,
"recipe_prep_time":"1.5 Hours",
"recipe_prep_steps":"Steps",
"recipe_ingredients":"12"
}
]
},
{
"recipe_filter":"Non Veg",
"recipe_array":[
{
"recipe_name":"Chicken Rezala",
"recipe_image":"chicken_rezala",
"isFavourite":false,
"isInCookList":false,
"recipe_prep_time":"2 Hours",
"recipe_prep_steps":"1234567",
"recipe_ingredients":"123"
},
{
"recipe_name":"Omu Rice",
"recipe_image":"omu_rice",
"isFavourite":false,
"isInCookList":false,
"recipe_prep_time":"1 Hour",
"recipe_prep_steps":"123456",
"recipe_ingredients":"12"
}
]
},
{
"recipe_filter":"",
"recipe_array":[
{
"recipe_name":"",
"recipe_image":"",
"isFavourite":false,
"isInCookList":false,
"recipe_prep_time":"",
"recipe_prep_steps":"",
"recipe_ingredients":""
},
{
"recipe_name":"",
"recipe_image":"",
"isFavourite":false,
"isInCookList":false,
"recipe_prep_time":"",
"recipe_prep_steps":"",
"recipe_ingredients":""
}
]
}
]
I want to fetch data in the recyclerview based on whether the recipe_filter is veg or non veg.
So guys, please give me pointers on how to fetch only the recipe_array value, veg or non veg recipes based on the recipe_filter value in this case.
First get value of your "recipe_filter" then after compare with your value Please check below code:
First Create json response POJO class:
public class RecipeResponse {
#SerializedName("recipe_filter")
#Expose
private String recipeFilter;
#SerializedName("recipe_array")
#Expose
private List<RecipeArray> recipeArray = null;
public String getRecipeFilter() {
return recipeFilter;
}
public void setRecipeFilter(String recipeFilter) {
this.recipeFilter = recipeFilter;
}
public List<RecipeArray> getRecipeArray() {
return recipeArray;
}
public void setRecipeArray(List<RecipeArray> recipeArray) {
this.recipeArray = recipeArray;
}
}
After getting successful json response Compare your recipe_filter value with veg or non veg.:
public void doRecipeSuccess(RecipeResponse mRecipeResponse){
if(mRecipeResponse.recipeFilter.equal("veg")){
// Write down veg code.
}else if(mRecipeResponse.recipeFilter.equal("non veg")){
// Write down non veg code.
}
}
Create POJO classes and then use GSON library a link
In your comment to Vishal Patolia's answer, you mention JSON querying. On Android without any libraries, an option for accessing JSON data is using the org.json library bundled within the Android Platform. While you can't-do a direct single query get to the data you want, you can get there programmatically querying your way towards your data.
Here is how you would get the recipe_array for "veg":
JSONArray json = new JSONArray(jsonString);
for (int i = 0; i < json.length(); i++) {
if (json.getJSONObject(i).getString("recipe_filter").equals("veg")) {
// Here is one recipe_array for veg
JSONArray someVegArrayData = json.getJSONObject(i).getJSONArray("recipe_array");
}
}
I recommend you go with Vishal's answer and use the Gson library or something similar to parse your JSON.
Try This
Main Activity
declare this on above of oncreate method
RecyclerView rv_myCart;
Adapter adapter;
ArrayList<HashMap<String,String>> all_list=new ArrayList<>();
in your on create method use this code
rv_myCart=(RecyclerView)findViewById(R.id.rv_completepurchase);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv_myCart.setLayoutManager(mLayoutManager);
rv_myCart.setItemAnimator(new DefaultItemAnimator());
adapter = new Adapter(all_list);
rv_myCart.setAdapter(adapter);
try {
JSONArray json=new JSONArray(strjson);
// Log.e(TAG, "json: "+json );
for (int i=0;i<json.length();i++)
{
HashMap<String,String> hashMap=new HashMap<>();
JSONObject jsonobject=json.getJSONObject(i);
// Log.e(TAG, "recipe_filter: "+jsonobject.getString("recipe_filter") );
hashMap.put("recipe_filter",jsonobject.getString("recipe_filter"));
JSONArray recipe_array=jsonobject.getJSONArray("recipe_array");
// Log.e(TAG, "recipe_array: "+recipe_array );
for (int j=0;j<recipe_array.length();j++)
{
JSONObject object=recipe_array.getJSONObject(j);
// Log.e(TAG, "recipe_name: "+object.getString("recipe_name") );
hashMap.put("recipe_name",object.getString("recipe_name") );
}
all_list.add(hashMap);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "e: "+e );
}
Adapter Class
Declare this in your adapter class
private List<HashMap<String,String>> myCartList;
your adapter method
public Adapter(List<HashMap<String,String>> myCartList) {
this.myCartList= myCartList;
}
in your onBindViewHolder method
HashMap<String,String> hashmap=myCartList.get(position);
if (hashmap.get("recipe_filter").equals("Veg"))
{
//todo when recipe_filter is veg
}
else
{
//// TODO: when recipe_filter is nonveg
}
Note:-still facing problem download full code from here

Custom deserializer for RealmObject

For learning purposes i'm creating an android app by using Realm and the Edinburg Festival Api. It's going pretty well except for one problem.
I'm using the following to convert the retrieved JSON to RealmObjects:
public void onResponse(final String response) {
realm.executeTransactionAsync(new Realm.Transaction(){
#Override
public void execute(Realm realm) {
// Update our realm with the results
parseImages();
realm.createOrUpdateAllFromJson(Festival.class, response);
}
}
}
This works fine except for one field, the images. The image part of the JSON:
"images": {
"031da8b4bad1360eddea87e8820615016878b183": {
"hash": "031da8b4bad1360eddea87e8820615016878b183",
"orientation": "landscape",
"type": "hero",
"versions": {
"large-1024": {
"height": 213,
"mime": "image/png",
"type": "large-1024",
}
"width": 1024
}
}
The problem here is the hash inside the image object. I have no clue how to handle this. The hash is different for every festival. Would it be possible to to make a custom JSON deserializer in my RealmObject?
Last code sample is my current model:
public class Festival extends RealmObject {
#PrimaryKey
public String title;
RealmList<Image> images;
public String description_teaser;
public String description;
public String genre;
public String age_category;
public String website;
public RealmList<Performance> performances;
public int votes;
}
I'm aware my PK is not optimal but this is still just testing to get the images working and i needed to set a PK for migrating.
Any tips are welcome, cheers :)
Update
Added the image model:
public class Image extends RealmObject {
public String hash;
public String orientation;
public String type;
RealmList<Version> versions;
}
Update 2
My attempt to parse the images before calling realm.createOrUpdateAllFromJson(Festival.class, response);
private void parseImages(String jsonString) throws JSONException {
JSONArray jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
JSONObject images = (JSONObject)jsonObj.get("images");
Iterator<String> iter = images.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = json.get(key);
realm.createOrUpdateObjectFromJson(Image.class,value);
} catch (JSONException e) {
// Something went wrong!
}
}
}
}
Update 3
I created a function that cleans up the broken JSON i get from the API. It ain't very nice but it works for now. it removes the hashes and the wierd versions and just places them both in a array. I'm sure it could be more efficiently written but i'll just go with this so i can move on with the rest of my app for now. See my own answer.
my own temporary solution:
/**
* Function to fix the json coming from the Festival API
* This is a bit more complicated then it needs to be but realm does not yet support #Serializedname
* It removes the "large-1024" (and simllar) object and places the versions in a JSON version array
* Then it removes the hashes and creates and images array. The JsonArray can now be parsed normally :)
*
* #param jsonString Result string from the festival api
* #return JSONArray The fixed JSON in the form of a JSONArray
* #throws JSONException
*/
private JSONArray cleanUpJson(String jsonString) throws JSONException {
JSONArray json = new JSONArray(jsonString);
for(int i = 0; i < json.length(); i++){
// We store the json Image Objects in here so we can remove the hashes
Map<String,JSONObject> images = new HashMap<>();
JSONObject festivalJson = json.getJSONObject(i);
JSONObject imagesJson = (JSONObject)festivalJson.get("images");
// Iterate each hash inside the images
Iterator<String> hashIter = imagesJson.keys();
while (hashIter.hasNext()) {
String key = hashIter.next();
try {
final JSONObject image = imagesJson.getJSONObject(key);
// Remove the version parents and map them to version
Map<String, JSONObject> versions = new HashMap<>();
JSONObject versionsJsonObject = image.getJSONObject("versions");
// Now iterate all the possible version and map add to the hashmap
Iterator<String> versionIter = versionsJsonObject.keys();
while(versionIter.hasNext()){
String currentVersion = versionIter.next();
versions.put(currentVersion,versionsJsonObject.getJSONObject(currentVersion));
}
// Use the hashmap to modify the json so we get an array of version
// This can't be done in the iterator because you will get concurrent error
image.remove("versions");
Iterator hashMapIter = versions.entrySet().iterator();
JSONArray versionJsonArray = new JSONArray();
while( hashMapIter.hasNext() ){
Map.Entry pair = (Map.Entry)hashMapIter.next();
versionJsonArray.put(pair.getValue());
}
image.put("versions",versionJsonArray);
Log.d(LOG_TAG,image.toString());
} catch (JSONException e) {
e.printStackTrace();
}
images.put(key,imagesJson.getJSONObject(key));
}
// Now let's get rid of the hashes
Iterator hashMapIter = images.entrySet().iterator();
JSONArray imagesJsonArray = new JSONArray();
while( hashMapIter.hasNext() ){
Map.Entry pair = (Map.Entry)hashMapIter.next();
imagesJsonArray.put(pair.getValue());
}
festivalJson.put("images", imagesJsonArray);
}
return json;
}
Hope it helps someone :) But sure ain't neat.
Due to how the keys are dynamic in this JSON (why isn't this an array? Whoever designed this API had no idea what they were doing), you'll have to manually parse the object up to the point of the hash key:
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject images = (JSONObject)jsonObj.get("images");
Iterator<String> iter = images.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = json.get(key);
realm.createOrUpdateObjectFromJson(Image.class, value.toString());
} catch (JSONException e) {
// Something went wrong!
}
}

Get JSONArray with Volley in Android

I'm trying to get this JSONArray with android but I can't get codigo and nombre of all items.
I leave the JSON that I'm trying to get:
{"categorias":
{"cfcd208495d565ef66e7dff9f98764da":{"orden":0,"codigo":"001","nombre":"TUBO Y ACCESORIO DE COBRE, LATON"},
"c4ca4238a0b923820dcc509a6f75849b":{"orden":1,"codigo":"002","nombre":"TUBO Y ACCESORIO PVC PRESION"},
"c81e728d9d4c2f636f067f89cc14862c":{"orden":2,"codigo":"003","nombre":"AISLAMIENTO"},
"eccbc87e4b5ce2fe28308fd9f2a7baf3":{"orden":3,"codigo":"004","nombre":"MONTAJE DE AGUA SANITARIA"},
"a87ff679a2f3e71d9181a67b7542122c":{"orden":4,"codigo":"005","nombre":"ABRAZADERAS FONTANERIA"},"e4da3b7fbbce2345d7772b0674a318d5":{"orden":5,"codigo":"006","nombre":"FLEXOS DE ACERO"},
"1679091c5a880faf6fb5e6087eb1b2dc":{"orden":6,"codigo":"007","nombre":"ACCESORIOS DE SANEAMIENTO"},
...
...
...
This is my code on Android, and I always get null response:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Respuesta:"+ response.toString());
try {
listaCategorias.clear();
int array=0;
JSONArray categorias = response.getJSONArray("categorias");
for (int i = 0; i < categorias.length(); i++) {
JSONObject objet = categorias.getJSONObject(i);
String titulo = objet.getString("nombre");
if (isIntegerParseInt(String.valueOf(titulo.charAt(0))))
listaCategorias.add(titulo);
}
array++;
onCallBack.onSuccess(listaCategorias);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("ErrorRespuesta: "+error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
its not an JSON ARRAY
Its JSON OBJECT
for your reference I'm posting sample json array
"three_day_forecast": [
{
"conditions": "Partly cloudy",
"day" : "Monday",
"temperature": 20
},
{
"conditions": "Showers",
"day" : "Tuesday",
"temperature": 22
},
{
"conditions": "Sunny",
"day" : "Wednesday",
"temperature": 28
}
]
Data was used by this reference.
It's not an Array but a JSONObject you need to modify your JSON to get an array with [] and not {}. Or you get it by getJSONObject.
With reference to the JSON String you've posted categorias is not a JSONArray. it's an object and the JSON string is still invalid.
On the top of the String you have the key as categories, now if you want to use that as an array you must have the value of categories to array which is specified within [ ] in JSON strings.
Another thing is try to avoid random key of the JSON Array if you're using it within loops with indexes. So your JSON String might look like following to support your Android code.
{
"categories": [
{ object 1... },
{ object 2... },
and so on...
]
}
You can see the type of JSON you will need here:
http://json-parser.com/53b37f69

Pulling data from a remote mySQL database, using AsyncTask; only displaying very last table row

As the title says really. I have two columns. I want to put them into textviews so I did it. However only the bottom two results, one from each column gets shown. Very odd. Here is my code: http://pastebin.com/qNgfHfT3
The parsing/onPostExecute is towards the bottom where the issue is.
One thing to note: The logs labeled "work" & "dontwork" show all my results, however the logs in the onPostExecute (Google & Google1) only show the last result so I presume the error is in the transfer from parsing to displaying.
Would really appreciate any help here. Thanks.
If you are receiving a JSON response I'd suggest you to parse it by using Gson. It's strongly recommendable as long as you can parse the whole thing in a pair of lines.
Note that creating a proper object it is as easy as doing the following:
YourObject object = gson.fromJson(responseReader, YourObject.class);
or even if you are retrieving a list of items:
Type listType = new TypeToken<List<YourObject>>() {}.getType();
List<YourObject> objects = gson.fromJson(responseReader, listType);
Here's an example that fits exactly your needs
After the process is done you'll have your object (or list of objects) available in an accesible variable.
EDIT:
First your Asynctask should have the following params:
public class HttpTask extends AsyncTask<Void, Void, ArrayList<Driver>> {
and your doInBackground method will need to pass that array to your onPostExecute:
#Override
protected ArrayList<Driver> doInBackground(Void... params) {
For the rest, I take it when the JSon parsing starts.
//PARSING JSON DATA
try {
JSONObject json_data;
Driver d;
jArray = new JSONArray(result);
int l = jArray.length();
if(l>0){
ArrayList<Driver> drivers = newArrayListList<Driver>();
for (int i = 0; i < l; i++) {
json_data = jArray.getJSONObject(i);
d = new Driver(json_data.optString("Driver_full_name"), json_data.optString("Drives_for"));
drivers.add(d);
Log.i("work", returnString);
Log.i("dontwork", somethingelse);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
CurrentSeasonDrivers_DriverName.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(CurrentSeasonDrivers_DriversName, "Could not parse data so shut up", Toast.LENGTH_LONG).show();
}
});
}
return drivers;
}
protected void onPostExecute(ArrayList<Drivers>... drivers) {
Log.i("Google", returnString);
Log.i("Google1", somethingelse);
String firstDriverName = drivers.get(0).name;
String firstDriverDrivesFor = drivers.get(0).drivesfor;
String secondDriverName = drivers.get(1).name;
TextView drivername = (TextView) findViewById(R.id.DriverName);
drivername.setText(firstDriverName);
TextView drivesfor = (TextView) findViewById(R.id.DrivesFor);
drivesfor.setText(firstDriverDrivesFor);
}
With this and an object for your driver will complete the circle.
public class Driver{
public String name;
public String drivesfor;
public Driver(String _name, String _drivesfor){
name = _name;
drivesfor = _drivesfor;
}
}
I guess you can take over from here.
Let me know about your progress.

Categories

Resources