Do something after volley request is processed - android

I was working on parsing the nested JSON objects using Volley and I got the answer from the stackoverflow itself.
Parsing Nested JSON Objects using Volley
But I think the code can be optimized without the if else and also I have to display a text "No Data" if the volley request is null or no data received. I tried to check using adapter.isEmpty, adapter.getCount()
None of it worked.
This is my code
datalist=false;
progressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
schemeslist=false;
progressBar.setVisibility(View.INVISIBLE);
try {
JSONObject obj = new JSONObject(response);
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
if(two.get("Rec") instanceof JSONArray) {
datalist=true;
JSONArray heroArray = two.getJSONArray("Rec");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
} else {
datalist=true;
JSONObject heroObject = two.getJSONObject("Rec");
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
// Toast.makeText(getApplicationContext(), " " + listView.getAdapter().getCount(),Toast.LENGTH_SHORT).show();
if(!datalist){
txtNoData.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
Can anyone tell me where should I put the if condition to work?
I checked with a toast for getting item count, but if there is no data, it is displaying blank and not 0. So I am not able to check

You can check size() of data list(heroList), size() is zero means you have no data.
try this
if(heroList.size() == 0){
txtNoData.setVisibility(View.VISIBLE);
}

Related

Volley request doesn't execute and no data are fetched

I have a simple URL that fetches some pics from pixabay website. with this URL: https://pixabay.com/api/?key=15507399-305bf88eb0892f7cdf58fb66b&image_type=photo&pretty=true&q=yellow+flowers.
Clicking on the link it is shown the JSON response. I want to get the "id" and "largeImageURL". but the method doesn't even execute. the Arraylist that is supposed to contain the values is always size = 0.
I have added the
<uses-permission android:name="android.permission.INTERNET"/>
I have no clue what I'm missing here
requestQueue = Volley.newRequestQueue(this);
loadImages();
//testing
String[] names = null;
for (int i = 0; i < images.size(); i++) {
names[i] = images.get(i).getId();
}
}
private void loadImages() {
String url = "https://pixabay.com/api/?key=15507399-305bf88eb0892f7cdf58fb66b&image_type=photo&pretty=true&q=yellow+flowers";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject pics = hits.getJSONObject(i);
images.add(new Flowers(pics.getString("id"), pics.getString("largeImageURL")));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "ha", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("test", "Error", error);
}
});
requestQueue.add(request);
}
Your code is working except that the placement of the block of codes '//testing' is at the wrong location resulting in size = 0. It takes time for the data to come in before 'onResponse()' get triggered and stores the data in 'images'. But you are already accessing the 'images' before 'onResponse()'.

Json Data Not Displaying in ListView

I am Trying to parse Json data into a list view
The list view is declared, and the Url I use is built with Uri.Builder, I have tested the URL with POSTMAN and it works and displays the data(on PostMan)
I am Using Volley to get the data
I can not figure out what the problem is
The code I use works for populating other list views but as soon as I add more paramaters, It shows blank
My Json data
{"success": 1,"Name": [{"ProjectDescription": "Project Name"},{"TaskCode": "VAL001"},{"TasDescription": "Value text
test"}]}
My Code
private void LoadTaskSpinner(String url) {
final ProgressDialog pd=new ProgressDialog(reportActivity.this);
pd.setMessage("Please Wait..Loading Time Log Data");
pd.setCanceledOnTouchOutside(false);
pd.show();
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String task=jsonObject1.getString("ProjectDescription");
String code=jsonObject1.getString("TaskCode");
String desc=jsonObject1.getString("TasDescription");
Project.add(task);
Project.add(code);
Project.add(desc);
}
}
report.setAdapter(new ArrayAdapter<>(reportActivity.this, android.R.layout.simple_spinner_dropdown_item, Project));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
Shiv Kumar, Suggested an Edit for me,
This Solved my Issue
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String key=jsonObject1.keys().next();
String task=jsonObject1.getString(key);
// String code=jsonObject1.getString("TaskCode");
// String desc=jsonObject1.getString("TasDescription");
Project.add(task);
//Project.add(code);
//Project.add(desc);
check if strings != null && strings != "" then add to the project.

Json Array response doesn't see value for item

I Know at first glance it's known mistake made by beginners but:
My standard response looks like this:
public ArrayList<Beer> jsonResponse(){
beerList.clear();
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
Constants.BASE_API_URL + Constants.BEER_LIST_URL_ENDPOINT,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject beerJsonObject = response.getJSONObject(i);
System.out.println(response.toString());
Beer beer = new Beer();
if (beerJsonObject.has("yeast")) {
beer.setYeast(beerJsonObject.getString("yeast"));
}
beer.setName(beerJsonObject.getString("name"));
beer.setIbu(beerJsonObject.getString("ibu"));
beer.setAlc(beerJsonObject.getString("abv"));
beer.setImgUrl(beerJsonObject.getString("image_url"));
beer.setId(beerJsonObject.getString("id"));
beer.setDescription(beerJsonObject.getString("description"));
beer.setFoodPairing(beerJsonObject.getString("food_pairing"));
beer.setFirstBrewed(beerJsonObject.getString("first_brewed"));
System.out.println(beer.getName()+" "+beer.getIbu()+" "+beer.getImgUrl());
beerList.add(beer);
}
beerRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
return beerList;
}
Everything works except "yeast" item:
if (beerJsonObject.has("yeast")) {
beer.setYeast(beerJsonObject.getString("yeast"));
}
without that if statement I've got standard json err. response no value for "yeast", I thought maybe not every object in response has this value and added that. But that doesn't helped, I still can't get that value, like it wouldn't exist in array, but it's not true, even in System.out.println(response.toString()) I can see a lot of "yeast" .
Here is example response from API I'm working with: https://api.punkapi.com/v2/beers
yeast is under ingredients
so should be:
if (beerJsonObject.has("ingredients")) {
JSONObject ingredients = beerJsonObject.getJSONObject("ingredients");
if (ingredients.has("yeast")) {
beer.setYeast(ingredients.getString("yeast"));
}
}

Parsing JSON to a recyclerview not Displaying

I'm doing an app that gets the nearby locations using JSON and displays them in a recyclerview. My problem is that, I'm really not sure what am I doing wrong here cause everything looks pretty well.
This is my code for reading JSON:
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data ...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLDATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
List_Item item = new List_Item(o.getString("name"), o.getString("reference"));
listItems.add(item);
System.out.println("My List Item: " + listItems);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
and this is my JSON structure:
This is my stackTrace:
You should set layout manager.
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
reycyclerview.setLayoutManager(layoutManager);

How to Get String from JSON Array [duplicate]

This question already has answers here:
JSON Array of strings (no objects), extracting data
(4 answers)
Closed 6 years ago.
its actually a simple code, cuz of lack of basic I still cant manage to handle this.
After I made a Post JSON Method on my own Api, I get the following response
[{"id":"2"}]
What I'm trying to achieve is that I would like to get the value of this "id" which is "2".
I've tried the following code in my private void method
private void getUserID() {
StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();
}
output.setText(idUser);
} catch (JSONException e) {e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I get it from here.
It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.
replace your try block with following
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String idUser = jsonObject.getString("id");
Log.e("id is: ", idUser);
}
Try this way you will get
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( delprourl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
// Parsing json
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person" + person);
//get your id here
String id = person.getString("id");
Log.e("id: ", id);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}

Categories

Resources