On the below code i want to use Response but it throws JSONException
StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Response: " + response);//output {"error":false}
try {
JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Sample JSON string:
{
"error": false,
"uid": "5b081af13eb974.69226352",
"user": {
"name": "66699",
"created_at": "2018-05-25 18:47:21"
}
}
How i should solve this?
Well, to retrieve the content of your response you don't need to use JSON while using POST request. Instead do something like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
in case of GET request you should do something like this :
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
try {
//put response into string
JSONArray Jresult = response.getJSONArray("user");
for (int i = 0; i < Jresult.length(); i++) {
JSONObject json_data = Jresult.getJSONObject(i);
String lName = json_data.getString("name");
String lCreatedAt = json_data.getString("created_at");
//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
_myUser.add(new User(lName, lCreatedAt));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);
Related
Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.
I am using Volley library to execute my rest APIs.
Using this I have sent email, password entries to URL and receiving response in JSON as:
{
"success": true,
"data": {
"message": false,
"token": "some token value"
}
}
Now I want to parse the 'token' field received from response and do further action. How can this be parsed?
This is the function where I want to parse the response.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")) {
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
I have seen this link How to parse JSON Object Android Studio but my "token" field is within another object, so not sure how to do it.
if you want to parse JSON in same manual way you have to do like this to get token.
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("success")== true) {
Toast.makeText(MainActivity.this, "UserExists", Toast.LENGTH_LONG).show();
JSONObject dataObj= jsonObject.getJSONObject("data");
String token= dataObj.getString("token");
////RETRIEVE "token" HERE
} else {
Toast.makeText(MainActivity.this, "User not registered", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is the solution
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject dataObj = response.getObject("data");
String token = dataObj.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
Please use POJO for parsing. Otherwise you will take more time to do this kind of work.
If you are using Volley, why not simply use the JsonObjectRequest:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// parse the response
JSONObject data= response.getObject("data");
String token = data.getString("token");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}
);
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
You can try like following.
public void parseData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")){
Toast.makeText(MainActivity.this,"UserExists",Toast.LENGTH_LONG).show();
////RETRIEVE "token" HERE
JSONObject dataObject = jsonObject.getObject("data");
String token = dataObject.getString("token");
}
else {
Toast.makeText(MainActivity.this,"User not registered",Toast.LENGTH_LONG).show();
}
}catch(JSONException e) {
Log.e("YourTAG","exceptions "+e.toString());
}
Hope it helps you.
How can I parse the following JSON using Android Volley?
[
{
"msg": "success",
"id": "1542",
"firstname": "Sam",
"lastname": "Benegal",
"email": "bs#gmail.com",
"mobile": "8169830000",
"appapikey ": "f82e4deb50fa3e828eea9f96df3bb531"
}
]
That looks like pretty standard JSON, so Volley's JsonObjectRequest and JsonArrayRequest request types should parse it for you. For example:
JsonArrayRequest request = new JsonArrayRequest(
Request.Method.GET,
"https://yoururl",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONArray response) {
JSONObject msg1 = response.getJSONObject(0);
String firstName = msg.getString("firstname") // Sam
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO
}
}
);
Code example adapted from the documentation, here: https://developer.android.com/training/volley/request#request-json.
try this
StringRequest stringRequest = new StringRequest(URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray1 = new JSONArray(response);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject object = jsonArray1.getJSONObject(i);
{
Toast.makeText(this, ""+object.getString("msg")+"\n"+object.getString("id"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
I am sending object with Post method in Volley. My api returns such a data like in postman and it is what i want.
{
"operationStatus": 3,
"messages": [
{
"message": "Hata!"
}
]
}
But I tried to get the such data my method in onResponse to handle. But it returns only 200.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
Toast.makeText(DetailAirdrop.this, response, Toast.LENGTH_SHORT).show();
}
Is there any way to get get jsonObject after post method in volley?
Solved
Solution:
JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, url,
jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(DetailAirdrop.this, response.toString(), Toast.LENGTH_SHORT).show();
}
try it :
Volley.newRequestQueue(getActivity()).add(new StringRequest(Request.Method.GET,"LINK", new Response.Listener<String>() {
#Override
public void onResponse(String s) {
JSONObject mJsonObject;
try {
mJsonObject = new JSONObject(s);
Toast.makeText(DetailAirdrop.this,
mJsonObject.getString("operationStatus") Toast.LENGTH_SHORT).show();
JSONArray mJsonArray = mJsonObject.getJSONArray("messages");
int a = mJsonArray.length();
for (int i = 0; i < a; i++) {
JSONObject jo = mJsonArray.getJSONObject(i);
Toast.makeText(DetailAirdrop.this,
mModel.setID(jo.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Crash", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}));
it will work i tested
and if it work tic my ansewer TY :)
i have a problem with my code and other post cannot helped me that's why i post here.
I'm getting some json from my php like
{
"lesMots":{
"1":{
"id":"4",
"wordFrench":"bite",
"wordEnglish":"dick"
},
"2":{
"id":"7",
"wordFrench":"pute",
"wordEnglish":"whore"
},
"3":{
"id":"2",
"wordFrench":"ordinateur",
"wordEnglish":"computer"
},
"4":{
"id":"1",
"wordFrench":"bonjour",
"wordEnglish":"hello"
},
"5":{
"id":"3",
"wordFrench":"monde",
"wordEnglish":"world"
}
}
}
Here is my Volley Request, i know i must use JSONObject for my JSONArray, but when i change it, the second JSONObject word ask me string and not int !
i'm trying to get 5 random french word and english word
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("lesMots");
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
textView.append(wordFrench+" "+wordEnglish+" "+" \n ");
Toast.makeText(getApplicationContext(), wordFrench +"",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error +"",Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
});
Thank for your help, i'm blocked on this problem and i'm kind of new in this.
If you need something more tell me
Try this, it will loop through the object based on the keys:
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
if (lesMots.get(key) instanceof JSONObject ) {
JSONObject obj = (JSONObject) lesMots.get(key);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
You have to change jsonarray to jsonobject.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonArray = response.getJSONObject("lesMots");
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
textView.append(wordFrench+" "+wordEnglish+" "+" \n ");
Toast.makeText(getApplicationContext(), wordFrench +"",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error +"",Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
});
the issue is that you have an obaject not an array solution can be this:
(where you response is the same you receive from the callback)
for example to mock this you can do:
String responseJson = "{\"lesMots\":{\"1\":{\"id\":\"4\",\"wordFrench\":\"bite\"," +
"\"wordEnglish\":\"dick\"},\"2\":{\"id\":\"7\",\"wordFrench\":\"pute\"," +
"\"wordEnglish\":\"whore\"},\"3\":{\"id\":\"2\"," +
"\"wordFrench\":\"ordinateur\",\"wordEnglish\":\"computer\"}," +
"\"4\":{\"id\":\"1\",\"wordFrench\":\"bonjour\",\"wordEnglish\":\"hello\"}," +
"\"5\":{\"id\":\"3\",\"wordFrench\":\"monde\",\"wordEnglish\":\"world\"}}}";
JSONObject response = new JSONObject(responseJson);
then in your callback
#Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMotsObject = response.getJSONObject("lesMots");
JSONArray jsonArray = lesMotsObject.toJSONArray(lesMotsObject.names());
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
...