JSONArray cannot be converted to JSONObject in Android - android

My Android app send request to REST API to authenticate user. Server return true with that request. But in my app run into onErrorResponse() withoud running into onResponse(). And the error I printed:
com.android.volley.ParseError: org.json.JSONException: Value [{"id":1,"username":"vuthehuyht","full_name":"Vũ Thế Huy","phone_number":"0972809817","password":"hoanglan"}] of type org.json.JSONArray cannot be converted to JSONObject
authenticateUser function
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", phoneNumber);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.53.100:3001/user/auth", jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login successfully", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
System.out.println(error.toString());
}
});
requestQueue.add(jsonObjectRequest);
user.controller.js
exports.auth = (req, res) => {
const phone_number = req.body.phone_number;
const password = req.body.password;
User.findAll({
where: {
phone_number: phone_number,
password: password
}
})
.then(data => {
res.send(data);
res.end();
})
.catch(err => {
res.status(500).send({
message: err.message | "Could not found user!"
});
res.end();
})
};
How can I fix it?

Just modify your Volley's request onResponse callback so accepts JSONArray as response instead of JSONObject, because that is the response type you are getting from your server:
#Override
public void onResponse(JSONArray response) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login successfully", Toast.LENGTH_SHORT).show();
}

if this is your response
[
{
"id":1,
"username":"vuthehuyht",
"full_name":"Vũ Thế Huy",
"phone_number":"0972809817",
"password":"hoanglan"
}
]
you may have to start with JSONArray LIKE
Try this Method
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "Url", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String Error = "";
try {
JSONArray jsonArray= new JSONArray();
for (int i = 0; i<jsonArray.length();i++){
JSONObject job = jsonArray.getJSONObject(i);
//So and So
progressDialog.dismiss();
}
} catch (JSONException e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);

Related

How do I solve Error org.json.jsonexception.No value fo login

I'm trying to login a registered user using their email and password from the registration credentials. How do I place value for login?
This is for a new xamp server. ,
private void Login( final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++ ){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
Toast.makeText(Login.this,
"Success login. \nYour Name : "
+name+"\nYour Email : "
+email, Toast.LENGTH_SHORT)
.show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +error.toString(), Toast.LENGTH_SHORT).show();
}
})
}

JSON Array Parsing using Android Volley without a TAG

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

volley android the list size in my code return Zero

please anyone help me the list size in my code return Zero
note:- list is global variable when get the size is return zero
public void getdata(String cities) {
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&APPID=8072ed7ede0fc9bcb8591a2a2eb90cfd";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
CityWeather cityWeather = new CityWeather();
JSONObject object = new JSONObject(response);
cityWeather.setLonitude(String.valueOf(object.getJSONObject("coord").getDouble("lon")));
cityWeather.setLatitude(String.valueOf(object.getJSONObject("coord").getDouble("lat")));
cityWeather.setCityName(object.getString("name"));
cityWeather.setCurrentTemp(String.valueOf(object.getJSONObject("main").getDouble("temp")));
cityWeather.setPressure(String.valueOf(object.getJSONObject("main").getInt("pressure")));
cityWeather.setHumidity(String.valueOf(object.getJSONObject("main").getInt("humidity")));
cityWeather.setMinTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_min")));
cityWeather.setMaxTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_max")));
cityWeather.setWindSpeed(String.valueOf(object.getJSONObject("wind").getDouble("speed")));
cityWeather.setWindDegree(String.valueOf(object.getJSONObject("wind").getInt("deg")));
list.add(cityWeather);
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
Thanks for all
Volley is not synchronous, it takes the request and give you the callback when the request is completed. If you check the size after onResponse is called you will get the desired result
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&APPID=8072ed7ede0fc9bcb8591a2a2eb90cfd";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
CityWeather cityWeather = new CityWeather();
JSONObject object = new JSONObject(response);
cityWeather.setLonitude(String.valueOf(object.getJSONObject("coord").getDouble("lon")));
cityWeather.setLatitude(String.valueOf(object.getJSONObject("coord").getDouble("lat")));
cityWeather.setCityName(object.getString("name"));
cityWeather.setCurrentTemp(String.valueOf(object.getJSONObject("main").getDouble("temp")));
cityWeather.setPressure(String.valueOf(object.getJSONObject("main").getInt("pressure")));
cityWeather.setHumidity(String.valueOf(object.getJSONObject("main").getInt("humidity")));
cityWeather.setMinTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_min")));
cityWeather.setMaxTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_max")));
cityWeather.setWindSpeed(String.valueOf(object.getJSONObject("wind").getDouble("speed")));
cityWeather.setWindDegree(String.valueOf(object.getJSONObject("wind").getInt("deg")));
list.add(cityWeather);
//Check list size here and do whatever you want with the list
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);

String to jsonObject

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

Unable to make jsonarrayrequest with volley

Im trying to make a post request with volley.
The request parameter is a json array .
Following is my request parameter
[
"Type",
{
"User": "email",
"password": "dimmer",
}
]
I have a method frameJsonArray that frames the above json and im making post request as follows,
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.POST, Constants.requestUrl, frameJsonArray(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
error.printStackTrace();
}
}
);
Im getting error in the above line of code where im making the request. How can I get this sorted?
Following is my error log
Error:(162, 46) error: constructor JsonArrayRequest in class JsonArrayRequest cannot be applied to given types;
required: String,Listener<JSONArray>,ErrorListener
found: int,String,JSONArray,<anonymous Listener<JSONObject>>,<anonymous ErrorListener>
reason: actual and formal argument lists differ in length
Following is my frameJsonArrayMethod
public JSONArray frameJsonArray() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("login_type", "Android");
jsonObject.put("username", email);
jsonObject.put("password", password);
jsonObject.put("short_name", null);
jsonObject.put("ip","123.421.12.21");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put("Login");
jsonArray.put(jsonObject);
Log.d(TAG, "he;ll " + jsonArray.toString());
Toast.makeText(getApplicationContext(), jsonArray.toString(), Toast.LENGTH_SHORT).show();
return jsonArray;
}
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
Source : http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
once check your JSON , wrong format , you missed double quote.
[
"Type",
{
"User": "email /** you missed double quote here **/,
"password": "dimmer",
}
]
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.POST, Constants.requestUrl, frameJsonArray(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
error.printStackTrace();
}
}
);
Change JSONObject to JSONArray in onResponse()
EDIT The error coming because there is only one constructor in JsonArrayRequest i.e.
public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener){}
source https://android.googlesource.com/platform/frameworks/volley/+/e7cdf98078bc94a2e430d9edef7e9b01250765ac/src/com/android/volley/toolbox/JsonArrayRequest.java
you are using some constructor with 5 arguments.

Categories

Resources