I have an AsyncHttpClient that makes a get request to an url.
I will take the response of the method onSuccess().
I paste my code to a better explain..
CategoryActivity.java call method getXML of class "XMLParser". In this method it is the AsyncHttpClient.
XMLParser parser = new XMLParser(URL);
xml = parser.getXML(URL);
XMLParser.java has .getXML(url) and return a String. I create a variable xmlResponse to put response value but it doesn't.
public String getXML(String url) {
// get connection..
String xmlResponse = "";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
super.onSuccess(response);
xmlResponse = response;
}
#Override
public void onFailure(Throwable e) {
ma.showUserAlertQuestion();
}
});
return xmlResponse;
}
How can I get back this value?
Thank you in advance & sorry for my bad english.
This is actually a race condition. The reason why you cannot get the value of xmlResponse is because your HTTP request is an asynchronous method, the result returned before it gets back the response from the server.
This answer basically explains everything, to get the response value of onSuccess(), you need to use an interface:
public Interface XMLCallback {
onSuccess(String response);
}
In your parser class:
public String getXML(String url, XMLCallback callback) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
super.onSuccess(response);
callback.onSuccess(response);
}
#Override
public void onFailure(Throwable e) {
ma.showUserAlertQuestion();
}
});
}
And in your activity class:
private String XMLResponse = "";
XMLParser parser = new XMLParser(URL);
xml = parser.getXML(URL, new XMLCallback() {
#Override
public void onSuccess(String response) {
XMLResponse = response;
}
});
I've got the same problem of you in other context. You can see it here: https://stackoverflow.com/questions/21578458/return-asynch-data-to-method-android-java
I am also searching for a solution, but didn't find it at this moment.
The reason why you get no results in your return value, is simple. When you do: client.get() the message is send to the server. Than your code goes inmediatly to return xmlResponse. The onSucces method will be called after the return, this is because the software reaches faster the return statement than the message from the Async call is returned by the server.
In the topic I showed you above is a solution for it. But that solution didn't fit for the way I planned my application. Maybe it will fit at your application.
Related
Im getting the "Value of type java.lang.String cannot be converted to JSONObject" error when trying to pass the response string to the JSON object. I've tried something similar in the past, and it worked, so I have no idea why it's happening.
Here's the code
public void searchMovie(){
OkHttpClient client = new OkHttpClient();
url = Constants.moviebaseurl + mEdit.getText();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String myResponse = response.body().toString();
SearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
JSONArray results = json.getJSONArray("results");
mText.setText(results.getJSONObject(0).getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
Am I doing something wrong, or am I just missing something? Thank you for your help!
It worked changing
final String myResponse = response.body().toString();
for
final String myResponse = response.body().string();
From referencing this question I was able to find this answer
Using google-gson you can do it like this:
JsonObject obj = new JsonParser().parse(myResponse).getAsJsonObject();
This question itself might even lead to some insight of the issue if my code doesn't work for you.
I am trying to integrate greendao with the retrofit. This link will give an idea ( https://i.stack.imgur.com/7qmbu.jpg) of how the data is sent to the server. It is a post request and I am really confused about how to call this request via retrofit.
It will be really helpful if someone can help me with it.
In API response I am getting an request object, response object, message and status code.
response object I have fields about the user and in request object I have field about the information that is being send.
another picture here
https://i.stack.imgur.com/a5DBz.jpg
You can create response like this using this method
private String create(String email, String password) {
try {
JSONObject cell1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
cell1.put("email", email);
cell1.put("password", password);
jsonObject.put("data", cell1);
return jsonObject.toString();
} catch (Exception e) {
return e.getMessage();
}
}
Call you POST as this
#FormUrlEncoded
#POST("your_path_here")
Call<String> uploadData(#Body String obj);
in your Activity
String json = create("your_email", "your_password");
apiInterface.uploadData(json).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
Hy!
I want to make some http calls to a restserver from my android client. I created a class for rest calls.
I followed the http://loopj.com/android-async-http/ description:
My question is that how can I send back anything from onSucces() method? For example I have the following function:
public class RestController {
public String getName() throws JSONException {
TwitterRestClient.get(url, null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
String name;
try {
name = response.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
How can I return the name to getName function?
function () {
...
String name = restController.getName();
...
do something with the name
Thank you very much!
I will apreciate any kind of help!
I'm trying to use setUseSynchronousMode on loopj to wait for results of http call before continuing in one case. I tried:
AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
Log.d("TEST", "Got results");
}
};
AsyncHttpClient client = new AsyncHttpClient();
responseHandler.setUseSynchronousMode(true);
client.get("http://www.google.com", responseHandler);
Log.d("TEST", "Don't want to get here until after getting results");
But the result is:
07-11 19:48:05.631 D/TEST﹕ Don't want to get here until after getting results
07-11 19:48:05.814 D/TEST﹕ Got results
Am I misunderstanding what setUseSynchronousMode should do?
You should have used SyncHttpClient instead of AsyncHttpClient. setUseSynchronousMode doesn't have the desired effect for AsyncHttpClient.
To have synchronous version of AsyncHttpClient with an ability to cancel it, I do everything on the main thread. Previously I was running it in AsyncTask and as soon as AsyncHttpClient.post() was called, the AsyncTask would finish and I was unable to keep track the AsyncHttpClient instance.
SyncHttpClient didn't allow me to cancel the uploading so I knew I had to use AsyncHttpClient and make appropriate changes.
Following is my class to upload a file which uses AsyncHttpClient and allows cancellation:
public class AsyncUploader {
private String mTitle;
private String mPath;
private Callback mCallback;
public void AsyncUploader(String title, String filePath, MyCallback callback) {
mTitle = title;
mPath = filePath;
mCallback = callback;
}
public void startTransfer() {
mClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
File file = new File(mPath);
try {
params.put("title", mTitle);
params.put("video", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mClient.setTimeout(50000);
mClient.post(mContext, mUrl, params, new ResponseHandlerInterface() {
#Override
public void sendResponseMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
// TODO convert instream to JSONObject and do whatever you need to
mCallback.uploadComplete();
}
}
#Override
public void sendProgressMessage(int bytesWritten, int bytesTotal) {
mCallback.progressUpdate(bytesWritten, bytesTotal);
}
#Override
public void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
mCallback.failedWithError(error.getMessage());
}
});
}
/**
* Cancel upload by calling this method
*/
public void cancel() {
mClient.cancelAllRequests(true);
}
}
This is how you can run it:
AsyncUploader uploader = new AsyncUploader(myTitle, myFilePath, myCallback);
uploader.startTransfer();
/* Transfer started */
/* Upon completion, myCallback.uploadComplete() will be called */
To cancel the upload, just call cancel() like:
uploader.cancel();
I'm using the Android Asynchronous Http Client. My code looks like this and is working fine.
DataUtil.post("RegisterUser", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String answer) {
// initialize variables
JSONObject json = new JSONObject();
String message = null;
try {
// turn string into JSONObject
json = new JSONObject(answer);
message = json.getString("message");
} catch (JSONException e) {
Log.e("ERROR", e.getMessage());
}
// registration was successful
if (message.equals("success")) {
// forward to login page
} else {
// error
}
}
});
I implemented a static HTTP Client. My server returns this JSON data {"message":"success"}. I do not want to treat it as a String and cast it back to JSON. But when I change it to public void onSuccess(JSONObject answer) eclipse tells me
The method onSuccess(JSONObject) of type new
AsyncHttpResponseHandler(){} must override or implement a supertype
method
The correct method signature would be this public void onSuccess(int statusCode, Header[] headers, JSONObject response) or any of the other available methods in the JsonHttpResponseHandler class