Parsing JSON to a recyclerview not Displaying - android

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);

Related

Textview not showing anything from JSON Object

Response from android is good which is the database i choose based on some value
Response: {"users":[{"id":"6","unique_id":"5f8fb2d3ee71c9.27038026","name":"siapa","email":"aku","encrypted_password":"G2HXPazvWEKRdm6lo5IDs4KSDEQ5ZTdlYjgyODBj","salt":"9e7eb8280c","created_at":"2020-10-21 11:02:27","updated_at":"2020-10-21 20:24:19"}]}
i need to show only object "updated_at" in textview but didnt show anything
this is my json code
private void getData() {
String tag_string_req = "get";
ArrayList<HashMap<String, String>> list_data;
list_data = new ArrayList<HashMap<String, String>>();
StringRequest strReq = new StringRequest(Method.GET,
AppConfig.URL_GET, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("updated_at", json.getString("updated_at"));
list_data.add(map);
}
update_time.setText(list_data.get(0).get("updated_at"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
what could be wrong?

Do something after volley request is processed

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);
}

Convert Json object to an array

I need help in modifying my android studio code for converting Json object to an array. Bellow is the error in my log cat and the actual code.
This is the error message I am getting in the logcat:
04-03 12:01:16.727 19993-19993/com.errandit E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"data":[{"errand":"Shopping","charges":"500"},{"errand":"House Assistance","charges":"7000"},{"errand":"Pick - Up","charges":"2500"}],"success":1,"message":" 0 records found"} of type org.json.JSONObject cannot be converted to JSONArray
**I am trying to fetch the json array from my wamp server using the method below. **
private void getData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.show();
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
Change like below as You are getting JSONObject and inside it there is JSONArray named "data".
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject mResponse)
{
JSONArray response=mResponse.optJSONArray("data")
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);

RecyclerView fill it with a Volley request doesn't show results

I'm having a problem with Volley and the RecyclerView.
In the onCreate Method of my Activity, I call a Volley Request to get data from my server. I then pass it to my Adapter as a List.
The thing is that everything is happening so fast when the onCreate method has finished my Volley Request hasn't finished yet, so nothing is displayed on the screen, how can I avoid this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__services__worker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Servicios");
final List services = new ArrayList();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Method.GET, AppConfig.URL_GET_SERVICES_REQUIRED, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag_servicio = jsonObject.getString("contratista");
String servicio = jsonObject.getString("descipcion_del_problema");
String zona = jsonObject.getString("zona");
String money = jsonObject.getString("precio_min");
//Toast.makeText(Activity_Services_Worker.this, tag_servicio+servicio+zona+money, Toast.LENGTH_SHORT).show();
services.add(new Servicios_worker(tag_servicio, servicio, zona, money));
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse (VolleyError error){
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(Activity_Services_Worker.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
recycler = (RecyclerView) findViewById(R.id.servicesAsked_RecyclerView);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new Adapter_services_required(services);
recycler.setAdapter(adapter);
}
In the add method, which I think is adding an element to the array of elements of the adapter, you should do notifyDatasetChanged() or you can do this:
...
final List services = new ArrayList();
;; CHANGED
recycler = (RecyclerView) findViewById(R.id.servicesAsked_RecyclerView);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new Adapter_services_required(services);
recycler.setAdapter(adapter);
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Method.GET, AppConfig.URL_GET_SERVICES_REQUIRED, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag_servicio = jsonObject.getString("contratista");
String servicio = jsonObject.getString("descipcion_del_problema");
String zona = jsonObject.getString("zona");
String money = jsonObject.getString("precio_min");
//Toast.makeText(Activity_Services_Worker.this, tag_servicio+servicio+zona+money, Toast.LENGTH_SHORT).show();
services.add(new Servicios_worker(tag_servicio, servicio, zona, money));
;; CHANGED
adapter.notifyDatasetChanged();
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse (VolleyError error){
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(Activity_Services_Worker.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);

Android Volley Not Updating URL data

When i run URL in browser its show with updated data but with Volley request URL data not update.
protected void getImagesArray() {
arrayList.clear();
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.show();
String url = "https://aditibendi3.000webhostapp.com/test_img/testarray.php";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressDialog.dismiss();
Log.e(TAG, "onResponse: " + response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = (JSONObject) response.get(i);
String image = jsonObject.getString("image");
model = new Model(image);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
gridAdapter = new GridAdapter(MainActivity.this, arrayList);
gridAdapter.notifyDataSetChanged();
gridView.setAdapter(gridAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e(TAG, "onErrorResponse: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
This is url response
[{"id":"11","image":"11.png"},{"id":"10","image":"10.png"},{"id":"9","image":"9.png"},{"id":"8","image":"8.png"},{"id":"7","image":"7.png"},{"id":"6","image":"6.png"},{"id":"5","image":"5.png"},{"id":"4","image":"4.jpg"},{"id":"3","image":"3.png"},{"id":"2","image":"2.png"},{"id":"1","image":"1.png"}]
and this is volley response
E/MainActivity: onResponse:
[{"id":"9","image":"9.png"},{"id":"8","image":"8.png"},{"id":"7","image":"7.png"},{"id":"6","image":"6.png"},{"id":"5","image":"5.png"},{"id":"4","image":"4.jpg"},{"id":"3","image":"3.png"},{"id":"2","image":"2.png"},{"id":"1","image":"1.png"}]
I have solved this issue by using this line
AppController.getInstance().getRequestQueue().getCache().remove(url);

Categories

Resources