I'm parsing a simple JSON response, and it is working when trying to parse the employer name, but it gets to a point where it will eventually crash and say that my 'review' json object, is empty. Here is the response:
https://raw.githubusercontent.com/vikrama/feed-json-sample/master/feed.json
And here is how I'm reading it:
private void extractName()
{
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject gimme = response.getJSONObject("response");
JSONArray resultsArray = gimme.getJSONArray("results");
for(int i = 0; i < resultsArray.length(); i++)
{
JSONObject info = resultsArray.getJSONObject(i);
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
}
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
adapter = new CompanyAdapter(MainActivity.this, companyNames);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage());
}
});
queue.add(request);
}
The debug line prints the correct values, then abruptly stops saying "no value for review". I'm pretty confused by this because it seems i'm reading through the data correctly. (use https://jsonformatter.org/json-viewer to better format this json i listed above)
Also, everything else in my recyclerview is set up properly, and the method extractName() is being called in the onCreate() method of my main activity.
This is happening because in some JSON Object you don't have "review" object, so it's throwing your code directly to catch Exception.
In order to overcome this, Please use:-
if(info.has("review")) {
JSONObject review = info.getJSONObject("review");
companyNames.add(review.getString("employerName"));
}
Instead of:
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
Related
when there is only one object, i dont have problem to retrieve variable from database
but when i want to retrive variable from only user1 or user2 the text in android doesnt appear anything.
this is my array from php code
{"users":[{"id":"5","name":"user1","updated_at":"2020-10-21 13:35:10"},{"id":"6","name":"user2","updated_at":"2020-10-21 11:29:53"}]}
and this my java code
private void getData(String name) {
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);
String pengguna = jsonObject.getString("name");
if (pengguna.contains(name)) {
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);
}
my question is how to get specific JSON object based on some variable? so the text in android only show text based on user.
edit : the problem already solved by some edit in php code, so only the object fetching from database based on user.
my response in android
{"users":[{"id":"6","name":"user2","updated_at":"2020-10-21 13:35:10"}]}
the problem right now is the textview doesnt show me the value although the response already correct
You can look up to follow this :
JSONObject jsonObject = new JSONObject();
jsonObject.getJSONObject("key");
It will resolve your problem, I think.
I have an API which send me a JSON object when I send a token to the server , I use GET method and I have to send token in body, not headers, it works in postman correctly when I put token in body but I have volley server error in android studio and I entered error response.here is my codes:
ant solution???? please
private void getFreightsFromServer()
{
final String url =" https://parastoo.app/api/driver-cargo-list";
JSONObject jsonData = new JSONObject();
String token = G.getString("token");
try
{
jsonData.put("token", token);
} catch (JSONException e)
{
e.printStackTrace();
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
boolean isGet = false;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(JSONObject response)
{
try
{
MyPost post = new MyPost();
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject tempJsonObject = jsonArray.getJSONObject(i);
JSONObject jsonOriginCustomer = new JSONObject(tempJsonObject.getString("origin_customer"));
post.setOriginCity(jsonOriginCustomer.getString("customerCity"));
JSONObject jsonDestinationCustomer = new JSONObject(tempJsonObject.getString("destination_customer"));
Log.d("result", jsonDestinationCustomer.getString("customerCity"));
post.setDestinationCity(jsonDestinationCustomer.getString("customerCity"));
freightsList.add(post);
// isGet = true;
adapter.notifyDataSetChanged();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
Log.d("jdbvdc", error.toString());
error.printStackTrace();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, jsonData, listener, errorListener);
Log.d("fhdhdcf",jsonData.toString());
final int socketTimeout = 100000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppSingleton.getInstance(getContext()).addToRequestQueue(request);
}
Please show the error message you have. Also I am not sure how ok it is to send something in a body of a GET request. This answer might help you:
HTTP GET with request body
It's better to use post method for this type of request.
But still if you want to use GET method then you should have to pass token in the URL.
Below is an example
final String username = etUname.getText().toString().trim();
final String password = etPass.getText().toString().trim();
URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;
I am new to Android and JAVA and I am trying to parse a json response. I know how to parse jsonarray but no Idea how to parse jsonobject. Can someone tell me how? Below is my Response.
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
And this is how parsed jsonarray.
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Please Someone help. Thanks.
In my opinion, use Gson library, where you give it the json object/array/string and it automatically parses it into a java object. Note that you have to define the java class with the appropriate fields.
EDIT: So here's an answer that goes with the suggested guidelines:
First create your model classes just like you will receive them from the server:
public class MyServerObject {
MyGarment jsonKeyName;
}
public class MyGarment {
String garment_color;
String garment_name;
String garment_price;
}
Next, after receiving your json string, parse it using Gson:
Gson gson = new Gson();
String json= "{"jsonKeyName":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"};
MyServerObject serverObject = gson.fromJson(json, MyServerObject.class);
Now, you can access your Garment object from your server object with all the values parsed correctly. Also note that if you're receiving a json array you could add the object as a list in your MyServerObject.class.
Hope this helps.
as per my above comment
you need to make JSONObject request instead of JSONArray request
try this to parse your JSON Response
try {
JSONObject jsonObject= new JSONObject("Response");
JSONObject jsonObject1=jsonObject.getJSONObject("118");
String garment_color=jsonObject1.getString("garment_color");
String garment_name=jsonObject1.getString("garment_name");
String garment_price=jsonObject1.getString("garment_price");
JSONObject jsonObject2=jsonObject.getJSONObject("119");
String garment_color2=jsonObject1.getString("garment_color");
String garment_name2=jsonObject1.getString("garment_name");
String garment_price2=jsonObject1.getString("garment_price");
} catch (JSONException e) {
e.printStackTrace();
}
Use StringRequest instead of JSONObject/JSONArray request and finally fetch value like this:
JSONObject object = new JSONObject(YOUR JSON RESPONSE);
String s1 = object.getJSONObject("118").getString("garment_color");
I'm getting the List<String> resultList response as empty in ResponseFinal log.But inside the loop the response is showing items in resultList
I don't understand why resultlist is returning empty outside the loop.Please help
public List<String> getParseJson(String sName)
{
final List<String> resultList = new ArrayList<String>();
String name=sName.replace(" ", "%20");
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.BASE_URL + "/suggest_item/items/"+name +"/"+ Constants.API_KEY,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Result handling
try {
JSONObject jsonObj = new JSONObject(response.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("Item");
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println( predsJsonArray.get(i).toString());
resultList.add(predsJsonArray.get(i).toString());
Log.e("Response",resultList.toString());
}
} catch (JSONException e) {
Log.e("JSOn", "Cannot process JSON results", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Error handling
System.out.println(error.toString());
}
});
// Adding request to request queue
Volley.newRequestQueue(context).add(stringRequest);
Log.e("ResponseFinal",resultList.toString());
return resultList;
}
My log :
E/Response: [1660309, 1660410]
E/ResponseFinal: []
declare List before oncreate() (defining the resultList at class level)
List<String> resultList = new ArrayList<String>();
You are returning list before response is coming that's why you are getting empty list. You can do something like below code which can get you list after response.
Step 1: Make a method name it onSuccess(List<String> list) with your getParseJson() method
public void onSuccess(List<String> list){
// do your code here after getting the list
}
//make this method as void
public void getParseJson(String sName){
//your code which you have already implemented
}
Step 2: call the above method from onResponse() method which is declared inside your getParseJson() method as follows:
#Override
public void onResponse(String response) {
// Result handling
try {
JSONObject jsonObj = new JSONObject(response.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("Item");
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println( predsJsonArray.get(i).toString());
resultList.add(predsJsonArray.get(i).toString());
Log.e("Response",resultList.toString());
}
} catch (JSONException e) {
Log.e("JSOn", "Cannot process JSON results", e);
}
//call here
onSuccess(resultList);
}
EDIT:
If you are calling getParseJson() from another class then call it as follows:
//If you are having paramaterized constructor then you can give parameter
new YourClassName(){
#Override
public void success(List<String> list) {
// do your code here after getting the list
}
}.getParseJson(String response);
The list in which you added is a copy and has scope only inside public void onResponse(String response). Hence, the actual list is empty as it was when defined. so, the final log displays empty.
I don't understand why resultList is returning empty outside the loop...
It is empty because your request runs asynchronously. So, you create your request along with response listeners, pass it to the Volley and then getParseJson() returns empty list - because request wasn't performed yet, and the other code will not wait for it to perform. After that, when request is performed (and it's performed asynchronously), your response listener adds the JSON values to the resultList but it's too late.
Rewrite your code so it handles the asynchronous nature of Volley requests.
Im trying to download data from a server in the form of a JSON object, parse that object then use the data elsewhere in my app.
Ive created a class which downloads the data (confirmed with a Log.v statement)
The trouble is that i want to display the results in a RecyclerView and the List of objects that i generate after parsing the JSON response does not get generated until after the adapter method is called from my main class.
So my question is, given the code below, how can i ensure that the on response method only exits once the parseResponse method has finished. Currently i am returning the (Null) _releaseList from my requestAndPareseReleaseList method.
public class ParseReleaseJSON extends JSONObject {
String _url;
List<ReleaseInfo> _releaseList = Collections.emptyList();
ParseReleaseJSON(String url) {
super();
_url = url;
}
public List<ReleaseInfo> requestAndParseReleaseList(Context _context){
JsonObjectRequest jsObReq = new JsonObjectRequest(Request.Method.GET, _url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
releaseList = parseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("err", "nosuccess");
}
});
MySingleton.getInstance(_context).addToRequestQueue(jsObReq);
return _releaseList;
}
private List parseResponse(JSONObject response) {
List<ReleaseInfo> list = new ArrayList<>();
if(response == null || response.length() == 0){
return list;
}
try {
if(response.has("results")){
JSONArray resultsArray = response.getJSONArray("results");
for(int i = 0, j = 6; i < j; i++){
ReleaseInfo release = new ReleaseInfo();
JSONObject tempObj = resultsArray.getJSONObject(i);
release.title = tempObj.getString("title");
release.date = tempObj.getString("date");
list.add(release);
}
return list;
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}