Android JSON get value - android

This is the JSON I have:
{"success":"1","message":"Login successful","firstname":"FIRST"}
How do I get the value 1 from success?
I have tried this:
public void startLogin(View v) throws JSONException {
EditText username = (EditText) findViewById(R.id.editUsername);
EditText password = (EditText) findViewById(R.id.editPassword);
String usr = username.getText().toString();
String pw = password.getText().toString();
String url = "hidden for privacy purposes";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray arr = new JSONArray(response);
JSONObject obj = arr.getJSONObject(0);
boolean success = obj.getBoolean("success");
if(success) {
Toast.makeText(getApplicationContext(), "LOGIN CORRECT", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "FAILED LOGIN", Toast.LENGTH_SHORT).show();
}
} catch(JSONException e) {
Toast.makeText(getApplicationContext(), "JSON error! " + e, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
queue.add(jsonObjectRequest);
}
}
This gives me a JSONException:
org.json.JSONException: Not a primitive array: class
org.json.JSONObject
This is my first time using JSON for anything, so I feel like a newbie. I have looked at some other questions posted on here and tried those solutions to no avail. If anyone could point me in the right direction or show me how to do this, I would greatly appreciate it.

You are entering a JSON object, not an array.

You don't need any initial transformation becuase using the JsonObjectRequest you are already obtaining a JsonObject as the response.
This means the object passed in the onResponse callback (response) is itself a JsonObject.
That said means you can directly query the object through the JsobObject API.
If success is a String you can do response.getString("success) or if it's an Int you do response.getInt("success") to retrieve success' data.

replace:
JSONArray arr = new JSONArray(response);
JSONObject obj = arr.getJSONObject(0);
with
JSONObject obj = new JSONObject(response)
you do not have an array as input

Related

JSON Array Request Parsing error using Volley Library

I'm working on a news application with api from newsapi.org. I'm using volley library for making JSONArrayRequest and getting data. I'm trying to get my head around json array and json object to understand the parsing. Unfortunately, I'm unable to parse the response. It always calls OnErrorResponse where the response is the json data. Can someone guide me how can I parse the response?
Response:
URL to site:
https://newsapi.org/docs/endpoints/sources
Parsing:
public void jsoncall() {
JsonArrayRequest arrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject;
Log.d("OnResponse", "" + response);
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("sources");
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Toast.makeText(getActivity(), "" + jsonObject1.getString("name"), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this,anime.toString(),Toast.LENGTH_SHORT).show();
lstAnime.add(anime);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getActivity(), "Size of Liste " + String.valueOf(lstAnime.size()), Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), lstAnime.get(1).toString(), Toast.LENGTH_SHORT).show();
setRvadapter(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("OnErrorResponse",""+error.toString());
}
});
requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
requestQueue.add(arrayRequest);
}
dear you are receiving JSONObject include "status" and "sources". I suggest to call JsonObjectRequest
Then parse your response to get JSONArray "sources" :response.getJSONArray("sources");

Android SharedPreference JSON not being accessed

I am using volley to send a http request to yahoo's weather API like this:
public Object requestData(String url) {
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
String responseList = response.toString();
cityList.edit().putString(String.valueOf(i), responseList);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(objectRequest);
return null;
}
As you can see, I am putting the response to this inside a sharedpreference I declared as "citylist"
:
cityList = getSharedPreferences(String.valueOf(i), MODE_PRIVATE);
I then access this response inside the sharedpreference like this:
String mResponse = cityList.getString(String.valueOf(i), "");
Log.d("log", mResponse);
try {
JSONObject jsonObj = new JSONObject(mResponse);
JSONObject response = jsonObj.getJSONObject("query");
createdCity.temperature = response.optJSONObject("results").optJSONObject("channel").optJSONObject("item").optJSONObject("condition").getInt("temp");
createdCity.conditions = response.optJSONObject("results").optJSONObject("channel").optJSONObject("item").optJSONObject("condition").getString("text");
createdCity.town = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("city");
createdCity.country = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("country");
createdCity.state = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("region");
Log.d("log", String.valueOf(createdCity.town));
cities.add(createdCity);
addMenuItemInNavMenuDrawer();
} catch (JSONException e) {
e.printStackTrace();
}
The problem is that "log" isn't outputting anything. The only information I'm getting from the logcat is:
org.json.JSONException: End of input at character 0 of
How can I go about fixing my issue? Is there a better way of doing this?
Are you committing after editing the preference? Based on your response, you might as well use apply() as it does things asynchronously.
If you are sure that the commit won't affect the main thread, you can use cityList.commit() or safely use cityList.apply(). But you need to do either of these two or else the changes are not written to the disk which is the reason you are not able to retrieve the data.
This link should help:
https://developer.android.com/training/data-storage/shared-preferences#java

Could not fetch JSON from http://anonymous-dtu.site11.com/

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

Try is working properly but catch is given error

Hey guys i am working in an app and i am verify my mobile number through OTP when i am send OTP to verify there is error mobile is verify but catch block is given error and Activity not going to next Acivity and not log is showing
private void verifyOtp(final String otp){
final StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_VERIFY_OTP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
boolean status =responseObj.getBoolean("status");
if (status==true) {
// parsing the user profile information
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
PrefManager pref = new PrefManager(getApplicationContext());
pref.createLogin(mobile);
Intent intent = new Intent(HttpService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(getApplicationContext(), "HTTPIF"+status, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "HTTPELSE"+status, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) { //------this is working and give toast----//
System.out.print("jsonError :=>"+e);
Toast.makeText(getApplicationContext(),
"Error is WWW: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "HTTPError: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
MyApplication userinfo = (MyApplication)getApplicationContext();
final String user = userinfo.getuser(); // Global Variable get Value uID
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("akey","xxxxxxxxxx");
params.put("mobileverify", otp);
params.put("uid",user);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
String mobile = profileObj.getString("mobile");
You may get no String but a null.
You are getting a JSONException. This may be due to many reasons and you will find them here: http://developer.android.com/reference/org/json/JSONException.html
The reason for this is, you are using a StringRequest. That means, the response is a plain String and not a JSON response. Just print out the reponse and see for yourself that it's not a valid JSON. What you need to use instead is a JSONRequest, or handle the String reponse as it is, instead of json parsing.
UPDATE:
Your problem might be because of either of the two lines below, since both of them can throw JSONException: getJSONObject() , getString()
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
You say your JSON response is {"msg":"verified","status":true}. Then how are you trying to fetch profileObj or the value for mobile ? If the value is not found for the key, it will throw JSONException. To avoid this, you need check if the value for the key exists. Use has(String key) to confirm a mapping for the key exists, before fetching it.

Android volley : how to check json type before parsing it

Is it possible to check the type of json beforehand? I'm somteimes getting an array and sometimes an object and I don't see how to handle these 2 cases without doing 2 different functions...
public void RequestApi( String url, final ApiResponse<ApiResult> completion )
{
Log.v("Performing request: ", url);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, hostname+url, (JSONObject) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.v("RequestApi Response", response.toString());
//Log.v("Data: ", response.toString());
try {
ApiResult res = new ApiResult();
Boolean success = response.getBoolean("success");
//here need to check type, sometimes array, sometimes object
JSONArray data = response.getJSONArray("data");
res.success = success;
res.data = data;
completion.onCompletion(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ApiResult res = new ApiResult();
res.success = false;
completion.onCompletion(res);
}
}
);
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Use StringRequest
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO something
}
});
Most simple solution - look at first string character. If it is { - object, if [ - array. But I think better to do following:
try {
JSONObject object = new JSONObject(value);
}
catch (JSONException) {
//if it throws, "value" contains not a JSONObject
JSONArray array = new JSONArray(value);
}
After going through the API I found a simple solution.
Since you are not sure of the return type, follow mentioned below steps.
First:
JSONArray arrayInstance = new JSONArray();// declare array instance to handle both the cases
Object objectInstance = rootObject.get(key); //key is the response string holding the value either jsonArray or jsonObject
Second:
if(objectInstance instanceof JSONArray){
arrayInstance = rootObject.getJSONArray(key);
}
else{
JSONObject tempObject = rootObject.getJSONObject(key);
arrayInstance.put(tempObject);
}
Third:
You can iterate though the array for the desired processing.

Categories

Resources