I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause. Here's the code:
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.getBoolean("status")) {
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
jsonObject.getInt("id"),
jsonObject.getString("username"),
jsonObject.getString("email")
);
// startActivity(new Intent(getApplicationContext(),UserActivity.class));
Toast.makeText(MainActivity.this, "User Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
And this is the JSON response
{
"status": "true",
"message": "Login successfully!",
"data": [
{
"id": "28",
"name": "Rr",
"username": "rr",
"password": "rr"
}
]
}
The value of id, username and email are placed into data object. And the data contains an array of objects. So you need to get the jsonObject from the data array and then you can find the value of id, username and email.
Try this
JSONObject jsonObject = new JSONObject(response);
JSONArray dataArr = jsonObject.getJSONArray("data")
JSONObject dataObject = dataArr.getJSONObject(0)
if (jsonObject.getBoolean("status")) {
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
dataObject.getString("id"),
dataObject.getString("username"),
dataObject.getString("email")
);
...
}
Update the whole code that you provided in this question. The whole code should be like this
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("status")) {
JSONArray dataArr = jsonObject.getJSONArray("data")
JSONObject dataObject = dataArr.getJSONObject(0)
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
dataObject.getString("id"),
dataObject.getString("username"),
dataObject.getString("email")
);
// startActivity(new Intent(getApplicationContext(),UserActivity.class));
Toast.makeText(MainActivity.this, "User Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
log the jsonObject , It will probably get the "data" array which you need to access it to get "id" value
JSONArray array = j.getJSONArray("data");
//reason to do 0 because only object is available
JSONObject dataObject = array.getJSONObject(0)
dataObject.getInt("id")
dataObject.getString("username"),
dataObject.getString("email")
Related
Good Day,
I am having a problem fetching my JSON file using Android Studio. How can I call a specific JSONObject for example on my code below I want to know if the inputted phone number is equals to the JSONObject number. I am trying to read the JSONArray and store in individually on different strings.
Every time I am trying to call obj.getString("phonenum") inside the loop the only value I am getting is the last value.
My code are as follow.
JSON File.
GetInfo.php
[
{
"id": 1,
"name": "Angelo Dayao",
"email": "angelo#gmail.com",
"phonenum": "639201234567"
},
{
"id": 2,
"name": "Angelo Dayao",
"email": "angelogg#g.com",
"phonenum": "639161234567"
},
{
"id": 3,
"name": "Anna Chelzia",
"email": "anna#g.com",
"phonenum": "639771234567"
}
]
JAVA FILE Code
public void GetData(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i = 0; i < jsonArray.length(); i++){
try {
JSONObject obj = null;
obj = jsonArray.getJSONObject(i);
if(obj.getString("phonenum") == phonenumber){
Toast.makeText(getApplicationContext(), obj.getString("phonenum"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} 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();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
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.
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);
I was looking for a Sample JSON data to test in my app. I found one on http://anonymous-dtu.site11.com/ and I have following code in my app(MainActivity) to retrieve this data:
private void getData() {
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Getting Data....");
dialog.setIndeterminate(false);
dialog.show();
StringRequest string = new StringRequest
(Request.Method.GET,
"http://anonymous-dtu.site11.com",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
try{
JSONArray array = new JSONArray(response);
Toast.makeText(MainActivity.this, String.valueOf(array.length()), Toast.LENGTH_SHORT).show();
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
String name = obj.getString("Name");
String email = obj.getString("Email");
String phone = obj.getString("Phone");
String city = obj.getString("City");
String country = obj.getString("Country");
ListItem l = new ListItem(name,email,phone,city,country);
listItems.add(l);
}
adapter = new MyAdapter(listItems, MainActivity.this);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Could not fetch", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(string);
}
But this could not fetch data and catches JSON exception.
Whats wrong with my code?
Thanks in advance!!
URL in which you're using will return html not json response. if you want to test with json request. my suggestion would be using the following github API
https://api.github.com/users/google
JSON EXCEPTION is here Line 483
"Country" : "Virgin Islands",
United States"
correct it as follow
"Country" : "Virgin Islands United States"
Bro Your Json Response is wrong..
Try Validation of your response here
http://jsoneditoronline.org
My volley throw error response when trying to parse JSON data inside listview. Is is because of my JSON data in object node, not array node.
JSON data
{
"users": [{
"userId": 1,
"name": "Dya Vega",
"profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "1 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 1 hour ago"
}, {
"userId": 2,
"name": "Esa Ezzatinor",
"profilePhoto": "https://graph.facebook.com/1269334432/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "2 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 2 hour ago"
}]
}
Code
// Creating volley request obj
JsonArrayRequest userReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
User user = new User();
user.setName(obj.getString("name"));
user.setProfilePhotoUrl(obj.getString("profilePicture"));
user.setLastActive(obj.getString("lastLogin"));
// adding movie to movies array
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Note:
=> if string contains { first character then string contain JSONObject as root container
=> if string contains [ first character then string contain JSONArray as root container
Posted json string contain JSONObject as root instead of JSONArray. use JsonObjectRequest instead of JsonArrayRequest for making request to server using Volley
You have users objects in an array inside an object. So you would want to start with a new JsonObjectRequest.
Edited: With the below code, you retrieve JSONObject type response, inside you have a JSONArray type users, after that you can loop through the JSONArray and retrieve each JSONObject from it.
JsonObjectRequest req = new JsonObjectRequest(URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = response.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
User user = new User();
user.setName(obj.getString("name"));
user.setProfilePhotoUrl(obj.getString("profilePicture"));
user.setLastActive(obj.getString("lastLogin"));
// adding movie to movies array
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MainActivity onErrorResponse
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setId(obj.getString(TAG_ID));
item.setNama(obj.getString(TAG_NAMA));
item.setAlamat(obj.getString(TAG_ALAMAT));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});