{
"status":"ok",
"cookie":"dr.steve|akscjn",
"cookie_name":"wordpress_logged_in",
"user": {
"id":330,
"username":"dr.steve",
"nicename":"steve",
"email":"steve#docdirect.com",
"url":"http:\/\/www.company.com",
"registered":"2016-12-15 22:21:05",
"displayname":"Dr.Steve",
"firstname":"Dr",
"lastname":"Steve",
"nickname":"steve",
"description":"Lorem ipsum",
"capabilities":"",
"avatar":null
}
}
I have this json response and i want the only id field from this json , I think there are two nested arrays but i am geting error
E/Error: Json parsing error: Value {"id":330,.........}at user of type org.json.JSONObject cannot be converted to JSONArray
this my code
if (jsonStr != null) {
try {
JSONArray ja = new JSONObject(jsonStr).getJSONArray("user");
JSONObject c = ja.getJSONObject(1);
String id = c.getString("id");
temp2 = id;
Log.v("id---->",temp2);
}
} catch (final JSONException e) {
Log.e("Error", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e("Error", "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
can anyone tell where i am making a mistake how would i get id field from this json ?
The user property is a concrete object not an array so try to read it as an object:
JSONObject user = new JSONObject(jsonStr).getJSONObject("user");
"user":{ is an object.
Arrays have square brackets. You have no arrays in your data
Related
I'm trying to do something similar to the answer of this question
I'm using Volley rather than Retrofit, and have adapted my code accordingly. For me the callback handlers never actually fire, although the counDownLatch does timeout after the specified number of seconds. I suspect the handlers never fire because the countDownLatch.awaiting is using all the processing on the current thread. Or am I missing something else?
public void queryUmbrellaServer() {
ArrayList<String> identifiers = getHardwareIdentifiers(context);
VolleyLog.DEBUG = true;
CountDownLatch countDownLatch = new CountDownLatch(identifiers.size());
// creating a new variable for our request queue
final RequestQueue[] queue = {Volley.newRequestQueue(context)};
queue[0].start();
for (int i = 0; i < identifiers.size(); i++) {
String url = umbrellaServerUrl + identifiers.get(i) + "/";
Log.i(LOG_TAG, "Inside Loop " + url);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
countDownLatch.countDown();
String serverName = response.getString("mdm_server_url");
String registrationUrl = response.getString("registration_url");
String isDeviceOwner = response.getString("device_owner");
Toast.makeText(context, "Retrieved server name from umbrella server: " + serverName, Toast.LENGTH_LONG).show();
setMdmInfo(serverName, registrationUrl, isDeviceOwner);
Log.i(LOG_TAG, "Successful response");
//queue[0].stop();
results.add(isDeviceOwner.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error in parsing response");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
countDownLatch.countDown();
if(error.networkResponse.data!=null) {
String jsonString = new String(error.networkResponse.data);
//Log.d(LOG_TAG, jsonString);
try {
JSONObject jsonObject = new JSONObject(jsonString);
String msg = jsonObject.getString("message");
if (!msg.equals("Device not found")) {
Log.d(LOG_TAG, "Error in retrieving response from server");
//queue[0].stop();
results.add("false");
}
else {
Log.d(LOG_TAG, "No device found");
results.add("false");
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error in retrieving response from server");
//queue[0].stop();
results.add("UNSET");
}
}
else {
Log.d(LOG_TAG, "Error in retrieving response from server");
//queue[0].stop();
results.add("UNSET");
}
}
});
// Add the request to the RequestQueue.
queue[0].add(jsonObjectRequest);
}
try {
countDownLatch.await(1L * identifiers.size(), TimeUnit.SECONDS); // join thread with timeout of second for each item
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(LOG_TAG,"outside loop" + results);
}
I expected the results arrayList should get populated before the countDownLatch countdown completes, but I haven't been able to get any results.
I am trying to parse an error body of a retrofit enqueue. The log shows the response.errorBody as
"{"response":["Image height must not exceed image width. Try a different image."]}"
Here is my code:
call.enqueue(new Callback<EditBlogResponse>() {
#Override
public void onResponse(Call<EditBlogResponse> call, Response<EditBlogResponse> response) {
if(response.body() != null){
Log.d(TAG, "onEditResponse: " + response.body());
editBlogResponse.setValue(response.body().toString());
}else{
try {
Log.d(TAG, "onResponseError: " + response.errorBody().string());
JSONObject jsonObject = new JSONObject(response.errorBody().string());
JSONArray jsonArray = jsonObject.getJSONArray("response");
editBlogResponse.setValue(jsonArray.getString(0));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<EditBlogResponse> call, Throwable t) {
t.printStackTrace();
editBlogResponse.setValue("failure");
}
});
I receive a system error
W/System.err: org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:460)
at org.json.JSONTokener.nextValue(JSONTokener.java:101)
at org.json.JSONObject.<init>(JSONObject.java:164)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.example.brandonblog.Repository.Repository$3.onResponse(Repository.java:176)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Any ideas on what I am doing wrong?
Well, in that case, your expected response is also inside the onResponse() block. you have to lookup into block for the 400 or 4xx status code like this:
if(response.code() != 200) {
Log.d(TAG, "onEditResponseCode: " + response.code());
Log.d(TAG, "onEditResponse: " + response.body());
editBlogResponse.setValue(response.body().toString());
} else {
Log.d(TAG, "onEditResponsecode: " + response.code());
Log.d(TAG, "onEditResponse: " + response.body().response.get(0));
//because your message is always at the 0th position of the 'response' list
// You don't need to use any JSONObject or JSONArray etc for these.
}
Try and let me know if it works.
Got it working, the problem was this line:
editBlogResponse.setValue(jsonArray.getString(0));
Instead of getString, it should be get():
editBlogResponse.setValue(array.get(0).toString());
Full working response:
public void onResponse(Call<EditBlogResponse> call, Response<EditBlogResponse> response) {
if(response.body() != null){
Log.d(TAG, "onEditResponse: " + response.body());
editBlogResponse.setValue(response.body().toString());
}else{
try {
JSONObject jObjError = new JSONObject (response.errorBody().string());
JSONArray array = jObjError.getJSONArray("response");
editBlogResponse.setValue(array.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My API returns this when I use wrong login information (using postman):
{
"error": {
"statusCode": 401,
"name": "Error",
"message": "login failed",
"code": "LOGIN_FAILED",
"stack": "Error: login failed\n at ...path..."
}
}
I am using this method to get the response message:
private void handleResponse(retrofit2.Response<Response> response) {
if (response.isSuccessful()) {
emailField.setText(null);
passwordField.setText(null);
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
} else {
try {
showSnackBarMessage(response.errorBody().string());
} catch (Exception e) {
showSnackBarMessage(e.getMessage());
}
}
}
And the output (what snackbar shows) is the same as postman returns.
handleresponse parameter retrofit2.Response<Response> response consists of retrofit2 Response, and my own <Response> class which looks like this:
public class Response {
#SerializedName("message")
#Expose
private String message;
public String getMessage() {
return message;
}
}
How can I get only message to show in snackbar?
I have tried the following code, but I get only No value for message.
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
According to your json the response error body is an object with a field error which contains a field message. This means you first need to get the error object and then the message:
JSONObject jObjError = new JSONObject(response.errorBody().string()).getJSONObject("error");
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
I am trying to add multiple records in database i am sending json array using string request method in volley in android to php script to add those records.But haven't getting the result of json array in php. I just want to add multiple records in mysql that why sending json array to script to add those records by fetching all data in it
Here is Insert Data function
private void InsertData() {
if(arrayList.size()>0) {
Toast.makeText(getApplicationContext(), "list not null "+i+arrayList.size(),
Toast.LENGTH_LONG).show();
//for (i=0;i<arrayList.size();i++) {
//Toast.makeText(getApplicationContext(),"inside for loop", Toast.LENGTH_LONG).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.insert_macthes,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} else
Toast.makeText(getApplicationContext(), "not added", Toast.LENGTH_LONG).show();
dis = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(MyMatchas.this,
"Error time out",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
Toast.makeText(MyMatchas.this,
"Auth Error time out",
Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
//TODO
Toast.makeText(MyMatchas.this,
"Server Error time out",
Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError) {
//TODO
Toast.makeText(MyMatchas.this,
" Network Error time out",
Toast.LENGTH_LONG).show();
} else if (error instanceof ParseError) {
Toast.makeText(MyMatchas.this,
"Parse Error time out",
Toast.LENGTH_LONG).show();
//TODO
}
}
}) {
#Override
protected Map<String, String> getParams() {
JSONArray array=new JSONArray();
JSONObject jsonObject=new JSONObject();
for(i=0;i<arrayList.size();i++)
{
Log.v("fetching record:",arrayList.get(i).getId());
arr[i]="dog_id"+arrayList.get(i).getId()+"dog_name"+arrayList.get(i).getDog_name()+"score"+arrayList.get(i).getDog_score()+"user_id"+ String.valueOf(SharedPrefManager.getInstance(MyMatchas.this).getUserid());
try {
//Log.v("put in json:",arrayList.get(i).getId());
jsonObject.put("dog_id",arrayList.get(i).getId());
jsonObject.put("dog_name",arrayList.get(i).getDog_name());
jsonObject.put("score",arrayList.get(i).getDog_score());
jsonObject.put("user_id",String.valueOf(SharedPrefManager.getInstance(MyMatchas.this).getUserid()));
} catch (JSONException e) {
Log.v("error exceptiion:",arrayList.get(i).getId());
e.printStackTrace();
}
array.put(jsonObject);
}
HashMap<String ,String> params=new HashMap<String, String>();
Log.v("All data:",jsonObject.toString());
Log.v("json object data:",array.toString());
params.put("params",array.toString());
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(MyMatchas.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
// }
// Toast.makeText(getApplicationContext(),dis,Toast.LENGTH_LONG).show();
}
Here is the Php script
<?php
$con=mysqli_connect("localhost","m","rt","Friend");
if($_SERVER['REQUEST_METHOD']=='POST'){
$arr = $_POST['params'];
$json = json_decode($arr,true);
echo $json;
foreach($json as $obj){
$Sql_Query = "INSERT INTO Match_list (dog_id,score,dog_name,User_ID) values
('$obj->dog_id','$obj->dog_name','$obj->score','$obj->user_id')";
if($con->query($Sql_Query) === TRUE)
{
die(json_encode(array("success"=>1,"message"=>"Data Added
Successfuly")));
}
}
}
mysqli_close($con);
?>
You can access values like this:
echo $json[0]["dog_id"];
You need to create new object for every time for holding new values
JSONArray array = new JSONArray();
JSONObject jsonObject;
GettingVaccineData gettingVaccineData;
for (int i = 0; i < vaccineData.size(); i++) {
jsonObject = new JSONObject();
gettingVaccineData = vaccineData.get(i);
try {
jsonObject.put("LCID", reqResponse);
jsonObject.put("LVID", gettingVaccineData.getID());
jsonObject.put("LVNAME", gettingVaccineData.getNAME());
jsonObject.put("LSCHEDULE", scheduleDays.get(i));
jsonObject.put("LGIVEN", "NULL");
jsonObject.put("LSTATUS", "not given");
jsonObject.put("LHOSPITAL", "NULL");
} catch (JSONException e) {
e.printStackTrace();
}
array.put(jsonObject);
I am getting a error in my code. The outer request returns a data but the inner loop returns null.
What I am doing here is: I am requesting some data and again using the id that I get from the first request, i use it to send another request. Although I am receiving the first response, I am getting ERRORNull message in the second nested request.
I am sure that the url is correct. I have not been able to find the solution to this problem.
private ArrayList<Item> fetchApiData(){
String url="http://www.gadgetsinnepal.com.np/wp-json/wp/v2/posts/";
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject item = (JSONObject) response
.get(i);
String id = item.getString("id");
String date = item.getString("date");
JSONObject titleobj = item
.getJSONObject("title");
String title= titleobj.getString("rendered");
String featuredMedia= item.getString("featured_media");
Toast.makeText(getApplicationContext(), "ID :" + id +" Date: "+ date+ " Title "+ title + featuredMedia,
Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
"http://www.gadgetsinnepal.com/wp-json/wp/v2/media/"+featuredMedia, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject nested_response) {
try {
// Parsing json object response
// response will be a json object
JSONObject guilld = nested_response.getJSONObject("guid");
String featured_img_url = guilld.getString("rendered");
String nestid=nested_response.getString("id");
Toast.makeText(getApplicationContext(),nested_response.toString()+"IMAGE" + nestid,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"ERROR"+error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
This problem was solved by carefully examining where the error log was giving.
Having unique logs in your methods will make finding the place where the problem occurs easier to find.
In this case we found that something was happening in:
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"ERROR"+error.getMessage(), Toast.LENGTH_LONG).show();
}
Further investigation showed we got a response code 503 message there.
Reasons for this to happen: lifewire.com/503-service-unavailable-explained-2622940
Increasing the time out of the request seems to prevent this from occurring again.