Android JSON VOlley - android

Good Day, I would like to get data from this url, and I have problems with onResponse method implementation:
I have something like this:
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//The Problem is here
JSONArray jsonArray = response.getJSONArray("");
String author = jsonArray.getString(0);
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
I don`t understand how to implement onResponse method correctly, I know that I must to get string from array or object, but data from link make me problems to understand what is it object or array, can you write me how to get author field from this url.
Thank you

Since the response in your link is JSONObject, you only need to do the following inside onResponse:
String author = response.getString("author");
textView.setText(author);
Hope this helps!

The response that you are getting is not a JSONArray but is a JSONObject. You could try the below code and see if you are able to get the author.
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String author = response.get("author");
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.

The data from link is JSONObject not JSONArray. Call response.getString("author"); to get author string.

try{
String author = response.getString("author");
} catch(JSONException e) {
e.printStackTrace();
}

Related

Not able to fetch JSON data [using volley Library] in Android

The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive

Writing JSON String as String in Android

I am creating an app which uses volley. I used JsonObjectRequest() to send Json object through volley. Thus I had to create Jason Object from values taken from Edit text.
btn_enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SN1 = inputsn.getText().toString();
Name1 = inputname.getText().toString();
}
});
JSONObject jsonMenu= null;
try {
jsonMenu = new JSONObject("");//string is to be added here
Toast.makeText(Add.this,"Made Obj",Toast.LENGTH_SHORT);
} catch (JSONException e) {
e.printStackTrace();
Log.d("Add","Error");
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,jsonMenu, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MainActivity",response.toString());
Toast.makeText(Add.this,"Response Received",Toast.LENGTH_SHORT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Add.this,"Error",Toast.LENGTH_SHORT);
}
});
RequestQueue queue= Volley.newRequestQueue(this);
queue.add(request);
Here, [{"SN":1,"Name":"Ajeeb"}] values 1 and Ajeeb is to be replaced by values of SN1 and Name1 respectively.Such that I can add it to Java code
JSONObject jsonMenu = new JSONObject("\\String goes here");
You can create property for json object and than as it to your Json Object
jsonMenu.addProperty("SN", SN1);
jsonMenu.addProperty("Name", Name);
This will result in {"SN":1,"Name":"Ajeeb"}
And if you want to create an array for it
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonMenu);
This will result in [{"SN":1,"Name":"Ajeeb"}]

Multiple object request using Volley Android

I want to call API Using Volley. There is an Multiple object Request So i don't Know Proper way. I was tried to code as below.But it does not give me Response.So can Anyone help me???
MainActivity
public void getJsonResponsePost(){
JSONObject jsonData = new JSONObject();
JSONObject json = new JSONObject();
/*{"data":{"lang_type":"1","keyword":"","latitude":23.022499999999997,"longitude":72.57139833333333,"category":6}}*/
try {
jsonData.put("data",json);
json.put("lang_type","1");
json.put("keyword","");
json.put("latitude",23.022499999999997);
json.put("longitude",72.57139833333333);
json.put("category",6);
Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("String Response :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(" Error getting :",error.toString());
}
});
jsonObjectRequest.setTag(REQ_TAG);
requestQueue.add(jsonObjectRequest);
}
I get the following response
StringĀ ResponseĀ :: {"status":"0","message":"Please pass the language type."}
Can you try this?
try {
json.put("lang_type","1");
json.put("keyword","");
json.put("latitude",23.022499999999997);
json.put("longitude",72.57139833333333);
json.put("category",6);
jsonData.put("data",json);
Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("String Response :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(" Error getting :",error.toString());
}
});

Volley Get Request: onResponse is never called

im pretty new to Android Studio and I'm trying to build a Get Request using Volley, the Server response is a JsonObject. I tested the code with breakpoints but I wonder why I don't jump into onResponse or why it won't work.
Here's my Code of the Get Method:
public Account GetJsonObject(String urlExtension, String name, Context context) {
String baseURL = "myurl.com/api";
baseURL += urlExtension + "/" + name;
// url will look like this: myurl.com/api/user/"username"
final Account user = new Account("","");
//Account(name, email)
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObject);
return user;
}
As #GVillavani82 commented your onErrorResponse() method body is empty. Try to log the error like this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
}
Make sure that you have the below permission set in AndroidManifest.xml file and the api URL is proper.
<uses-permission android:name="android.permission.INTERNET"/>
And JsonObjectRequest class returns Asynchronous network call class. Modify your code like below.
// remove Account return type and use void
public void GetJsonObject(String urlExtension, String name, Context context) {
....
.... // other stuffs
....
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
processResponse(response); // call to method
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
});
requestQueue.add(jsonObject);
}
Now create another method like below
private void processResponse(JSONObject response) {
try {
final Account user = new Account("","");
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
} catch (JSONException e) {
e.printStackTrace();
}
}

Retrofit updating class PUT error code 301

Maybe this is a silly question but I've been stucked on this for a while. I'm implementing some methods for a restApi. I'm using retrofit and I'm trying to update a client information. To do an update I'm using PUT method but I don't know why I'm always getting a 301 CODE and I can't update the information. Here is my code, thank you for everything.
public interface ClientInterface {
#GET("/clients/{clientParam}")
public Client fetchClient(#Path("clientParam") String client);
#GET("/clients/")
public void fetchAllClients(Callback<List<Client>> callback);
#POST("/clients/")
public void newClient(#Body Client client, Callback<Client> callback);
#PUT("/clients/{clientParam}/")
public void updateClient(#Path("clientParam") String cod, #Body Client client,Callback<Client> callback);
}
After that I use the update method in the following way
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Utils.getURLPreferences(DatosClienteActivity.this)).build();
ClientInterface clientRestInter = restAdapter.create(ClientInterface.class);
Client clientsUpdate = new Client();
//Fetch data into clientsUpdate object
clientRestInter.updateClient(codClient, clientsUpdate, new Callback<Client>() {
#Override
public void success(Client client, retrofit.client.Response response) {
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
EDIT:
If I use volley against the same URL it's working perfectly...
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
try {
//Construct jsonObject
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.PUT, URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
error.printStackTrace();
}
});
queue.add(req);
Finally I solved it.
The problem was that we had two different Client objects and the one that you fetch is the one that you must change and use it to upload with PUT.
I hope that this help somebody.

Categories

Resources