Volley onResponse method not triggered - android

I am trying to parse a JSON file and fetch certain info from every person in the JSON file. I have created a parseJSON() function to do this for me, but I have run into a problem. The application works but it does not receive the information from the JSON file. After placing a breakpoint in the function, I realised that the application does not even acess the onResponse() function.
I have read the answers of some similar questions like this, but they did not seem to be of help.
What seems to be the cause of this?
parseJson() function:
private void parseJson() {
JsonArrayRequest request = new JsonArrayRequest(jsonUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
JSONObject nameObject = jsonObject.getJSONObject("name");
String title = nameObject.getString("title");
String firstName = nameObject.getString("first");
String lastName = nameObject.getString("last");
String email = jsonObject.getString("emial");
JSONObject prictureObject = jsonObject.getJSONObject("picture");
String imageUrl = prictureObject.getString("medium");
String fullName = title + " " + firstName + " " + lastName;
Log.e("FULL NAME", fullName);
// Ignore this part
/*Book jsonBook = new Book(imageUrl, fullName, email, 50.0, 100, 3);
Books.add(jsonBook);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(HomeActivity.this);
}
}
link to my json file: https://api.myjson.com/bins/ldql7

You are doing a JsonArrayRequest when it needs to be a JsonObjectRequest. The body of your JSON file is contained within a Json Object:
{
"results": [...]
}
Once you have changed the request type, modify your parseJson method like so:
private void parseJson() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, "https://api.myjson.com/bins/ldql7", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
try {
JSONArray array = response.getJSONArray("results");
JSONObject jsonObject = null;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
JSONObject nameObject = jsonObject.getJSONObject("name");
String title = nameObject.getString("title");
String firstName = nameObject.getString("first");
String lastName = nameObject.getString("last");
String email = jsonObject.getString("email");
JSONObject prictureObject = jsonObject.getJSONObject("picture");
String imageUrl = prictureObject.getString("medium");
String fullName = title + " " + firstName + " " + lastName;
Log.e("FULL NAME", fullName);
// Ignore this part
/*Book jsonBook = new Book(imageUrl, fullName, email, 50.0, 100, 3);
Books.add(jsonBook);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}

Related

how to POST jsonobject with volley

I am developing a chatroom and have a this request to get jsonArray from my db, and i want to do a POST jsonObject request to insert msg in db:
public void getMsg(){
String url = "http://192.168.1.57/android/leggi.php";
final TextView chatView =(TextView) findViewById(R.id.chat);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
String msg = "";
String mittente = "";
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i<response.length(); i++) {
try {
mittente = response.getJSONObject(i).get("mittente").toString();
} catch (JSONException e) {
e.printStackTrace();
}
try {
msg += (response.getJSONObject(i).get("mittente").toString() + ":\n" + response.getJSONObject(i).get("testo").toString() + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
chatView.setText(msg);
//chatView.setGravity(Gravity.RIGHT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest);
}
can i use the same volley request??? or the request must have different params??? need help :P
This depens on what your servers response is when POSTing the JSONObject.
If the server responses with an JSONArray, you can build your response the same way:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.POST, url, INSERT_HERE, new Response.Listener<JSONArray>()
...
{
And insert the JSON Object you want to post at the INSERT_HERE position.
If your response differs you need to change the type of Response.Listener<JSONArray>

Adding volley response to global variables

I have using volley library for fetching data. I used a HashMap to store response data. When I fetch the data out of the volley request it is showing empty. I knew I should use this Hashmap inside the response method. But I need to get that in a global variable. Any suggestions?
String liveURL = BASE_URL + "livescores?api_token=" + API_KEY;
HashMap<String, String> hashMap = new HashMap<>();
JsonObjectRequest livescoresRequest = new JsonObjectRequest(Request.Method.GET,
liveURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
final JSONArray liveArray = response.getJSONArray("data");
for (int i = 0; i < liveArray.length(); i++) {
JSONObject data = liveArray.getJSONObject(i);
String liveID = data.getString("id");
final String league_id = data.getString("league_id");
hashMap.put(league_id, liveID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
});
Volley.newRequestQueue(getContext()).add(livescoresRequest);
Log.i("HASHMAP", hashMap.toString());

How to parse Json data with object class from url using AQuery

This is my code and I am having error to parse data from object, what changes can be done so as to parse data...
aQuery.ajax(fetch_url, JSONObject.class, new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject obj, AjaxStatus status){
super.callback(url, obj, status);
Log.i("response", url + "response:" + obj);
ArrayList<UserInfo> list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("org_list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
UserInfo info = new UserInfo();
info.id = object.getString("Id");
info.servicename = object.getString("name");
info.amount = object.getString("amount");
list.add(info);
});
}
And this is my JSON data format
{
"org_list": [
{
"Id": "1",
"name": "CBC-Test",
"amount": "200"
}
]
}
When i edit from the below code and now i am facing null response value. I have also attached my logcat image file for further more details about my problem:Click here
Click here for further more details in my code
Logcat View1
Logcat View2
Edit your code as below,
aQuery.ajax(fetch_url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject obj, AjaxStatus status) {
super.callback(url, obj, status);
Log.i("response", url + "response:" + obj);
ArrayList<UserInfo> list = new ArrayList<>();
try {
JSONArray jsonArray = obj.getJSONArray("org_list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
UserInfo info = new UserInfo();
info.id = object.getString("Id");
info.servicename = object.getString("name");
info.amount = object.getString("amount");
list.add(info);
}
} catch (Exception e){
e.printStackTrace();
}
}
});
No need to re-create object of JsonObject. Just use that from response.
Finally I searched my self and found a solution. But it is without using AQuery and it is by using RequestQueue...
txtview = findViewById(R.id.showdata);
Button buttonParse = findViewById(R.id.showbtn);
requestQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
jsonParse();
}
});
}
public void jsonParse(){
String fetchurl = "http://use your url here.com/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, fetchurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("org_list");
for (int i=0; i < jsonArray.length(); i++){
JSONObject patient = jsonArray.getJSONObject(i);
String firstName = patient.getString("orga_organame");
txtview.append(firstName+","+"\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}

How to update json data using volley method on Android?

I get the error no value for city.
I'm new to Android. I was unable to pass the spinner data using PHP URL, volley method. And in my XML I'm using the spinner and text views city, id and pass the city list through spinner URL.
Here is my activity:
private void spinnerapi(){
sprCoun = (Spinner) findViewById(R.id.spinner);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String serverURL = "server url";
final StringRequest getRequest = new StringRequest(Request.Method.POST, serverURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("officerResponse", response);
try {
JSONObject jsonObject = new JSONObject(response);
String str_status = jsonObject.getString("status");
String str_message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectGuest = jsonArray.getJSONObject(i);
city_name = jsonObjectGuest.getString("cityname");
city_id = jsonObjectGuest.getString("cityid");
listarraylist.add(new CityModel(city_name));
}
sprCoun.setAdapter(new ArrayAdapter<String>
(RegistrationActivity.this, android.R.layout.simple_spinner_dropdown_item, list));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG).show();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
// Toast.makeText(context, "" + error, Toast.LENGTH_LONG).show();
Log.d("tyghj", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
queue.add(getRequest);
}

Index 0 out of range [0...0]

I am getting this in my Json method.
I am trying to get information from my server and mysql database and then display it in my username text view.
This is my Json Method. It throws the index out of range error.
private void showJSON(String response) {
String username = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Constantss.JSON_ARRAY);
JSONObject profileData = result.getJSONObject(0);
username = profileData.getString(Constantss.USERNAME);
System.out.println("first" + username);
} catch (JSONException e) {
e.printStackTrace();
}
usernameView.setText(username);
System.out.println("second" + username);
}
Probably not needed but this is how I am getting my data, It works fine I am able to retrieve the Id and also run the php code to give me the username.
private void getData() {
class lata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), //Context
"us-east--------------", //Identity Pool ID
Regions.US_EAST_1 // Region
//Now we retrieve
);
// return null;
String identityID = credentialsProvider.getIdentityId();
Log.d("LogTag", "my ID is" + identityID);
String id = identityID;
String userid = identityID;
System.out.println("Id is" + identityID);
System.out.println("Id tis" + id);
String url = Constantss.PROFILE_URL + identityID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Profile.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Profile.this);
requestQueue.add(stringRequest);
return identityID;
}
}
lata pasta = new lata();
pasta.execute();
}
Probably the length of your array is 0. Please check it.
You can try verifying the response var in
private void showJSON(String response) {
Is not empty
Use Gson to decode the json will be much more convenient than the way you did , and obviously the JSONArray result's length is 0

Categories

Resources