Accessing volley response in another class/method - android

I am beginning in my journey in Android development so might be doing this all wrong. I am trying to get a set of data using Volley and display it which is ok.
The next step I need to do is use the data to make further requests.
The first request gets a list of sports teams.
I then want to make a request for each team to get the players.
Ideally what I'd like to do is make the first request and return the JSONobject to be used with another class. I have no idea how i would do this.
teamData.getTeams(
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//i want to get this out somehow
JSONObject thing = response;
}//end on response
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
}
});
I'm happy to expand on this if need be.

Volley is enqueuing the request so it fires a request after the older one has returned success or error.
So you can enqueue a new request in the success of the older.
Exemple : in your response of your team request you add a new request as you did JSONObject thing = response;
This is an exemple of mine witch imports multiple projects and then imports each project infos:
public void importProjects() {
Response.Listener<JSONArray> jsonArrayResponseListener;
String url = Globals.getApiBaseUrl() + GET_PROJECTS_URL;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
ArrayList<Project> projects = MyJsonParser.getInstance().parseProjects(response);
if (projects.size() > 0) {
for (Project p : projects) {
importProject(p); //####### HERE IS THE KEY :: this methode is the same of this one. It calls other volley request.#######//
}
}
} catch (Exception e) {
Log.e("SyncRngine", "THIS IS AN ERROR");
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = formatUrl(url, params);
Log.i("URL IMPORT PROJECTS", url);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}
And now the défénition of importProject(Project p) :
public void importProject(final Project project) {
String url = Globals.getApiBaseUrl() + GET_PROJECT_URL;
Response.Listener<JSONArray> jsonArrayResponseListener;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
useProjectInfos(response);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = url + "/" + project.getProjectID();
url = formatUrl(url, params);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}

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

I want to access local server with port to get json as respose

I want to get json response from local server. I want to add port in that. how to add port while using volley in android
In main activity
{
String url = "192.2.3.1:80/data";
sendAndRequestResponse(url, new VolleyCallback(){
#Override
public void onSuccess(JSONObject result){
}
});
}
private void sendAndRequestResponse(final String url, final VolleyCallback callback) {
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(MainActivity.this, new ProxyPort());
//String Request initialized
mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show();//display the response on screen
Log.e("url", url);
Log.e("Response", response.toString());
try {
JSONObject obj = new JSONObject(response);
callback.onSuccess(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERR", "Error :" + error.toString());
}
});
VolleyLog.DEBUG = true;
mRequestQueue.add(mStringRequest);
}
I want to add port in this url. I want to access local host using ip. How to achieve it

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

HTTP POST request with different format of the url

I am developing an Android app for a Company. While working on the API the company guys gave me a login API something like this
"app.abc.com/Login?data={"email":"abc","pwd":"123"} "
I am using volley library but I don't know how to post data like this since I have not done it before.
I need advice and wanted to know if this is the right way.
Instead of volley ..try to use android networking library
--to do this :add
--compile 'com.amitshekhar.android:android-networking:0.4.0'
to your gradle file.enter code here
AndroidNetworking.post("your login URL")
.setTag("Login")
.addBodyParameter("email", "abc")
.addBodyParameter("pwd", "123")
.setPriority(Priority.IMMEDIATE)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataJson = response.getJSONObject("data");
boolean status = dataJson.getBoolean("success");
} else {
JSONArray errorJsonArray = dataJson.getJSONArray("errors");
String errorMsg;
for (int i = 0; i < errorJsonArray.length(); i++) {
errorMsg = errorJsonArray.get(i).toString();
Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
}
Log.e("Error", response.toString());
}
} catch (JSONException je) {
je.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
try {
if (anError.getErrorBody() != null) {
JSONObject jsonObject = new JSONObject(anError.getErrorBody());
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(), dataJsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), anError.getErrorDetail(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Error", anError.getErrorDetail());
}
});
Using Volley - Create the request queue
RequestQueue queue = Volley.newRequestQueue(this); // this = context
Then create the postRequest, should look somthing like (using Volley):
url = "app.abc.com/Login";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("data", "{\"email\":\"abc\",\"pwd\":\"123\"}");
return params;
}
};
queue.add(postRequest);
I also recommend using Retrofit and GSON libraries (a bit learning curve here but it is worth it since they are very powerful libraries)

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