Hey i'm using AsynHttpClient.
I would like to implement my get and set functions in one Activity where they can get called by others.
But how can i call my custom callback from the reponse callback?
I dont get it how it works in an inner class
public void requestApiUrl(Callback callback ){
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("AppKey",getResources().getString(R.string.AppKey));
AsyncHttpClient client = new AsyncHttpClient();
StringEntity entity = null;
try {
entity = new StringEntity(jsonObj.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.get(this, "***************URL***********", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject utils) {
super.onSuccess(statusCode, headers, utils);
Log.d("HTTP", "response: " + utils.toString());
callback.reponse();
}
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("Failed: ", "" + statusCode);
Log.d("Error : ", "" + throwable);
callback.reponse();
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
As far as i could get out of your question, you need to call a function from child/inner class where the function belongs to the parent/outer class. Quoting the answer from this question
For a class
class Outer {
void show() {
System.out.println("outter show");
}
class Inner{
void show() {
System.out.println("inner show");
}
}
}
you can simply call
Outer.this.show();
Related
I'm using android-async-http for rest request. When I doing post request then the response body is empty. When I use postman for the same request I received a response as JSONObject.
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(getResources().getString(R.string.api_user), getResources().getString(R.string.api_password));
String requestAddress = getResources().getString(R.string.api_base_address) + getResources().getString(R.string.api_event_address);
JSONObject params = new JSONObject();
params.put("name", mEditTextName.getText().toString());
params.put("place", mEditTextPlace.getText().toString());
params.put("dateAndTime", DateUtils.sdfWithFullTime.format(DateUtils.sdfWithTime.parse(mEditTextDate.getText().toString())));
Log.d(TAG, "onClick: " + params.toString());
StringEntity stringParams = new StringEntity(params.toString());
client.post(getApplicationContext(), requestAddress, stringParams, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "onFailure: error during creating event " + responseString,throwable );
Toast.makeText(getBaseContext(),"Error during creating event",Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(getBaseContext(),"Successfully create event",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), EventListActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
Log.e(TAG, "createEvent: error during creating event", e);
}
}
Check parameters and base url, use volley or retrofit library to Post request.
I m posting JSON in raw with this Url [URL I post data to][1]
param is=eventName="countryList"
codes
private void testApp() {
try {
JSONObject jsonParams = new JSONObject();
jsonParams.put("key", "value");
StringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(), "url", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("good",response.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail",throwable.toString());
}
});
} catch (Exception e) {
}
}
error:fail: cz.msebera.android.httpclient.client.HttpResponseException: Internal Server Error
change fromStringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
to:**StringEntity stringEntity = new StringEntity(jsonParams.toString());**
And Also override
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
your response return jsonobject not array
I am trying to upload a file using AsyncHttpClient.Below is the code :
public class uploadVideoAsyncTask extends AsyncTask<String,Void,JSONObject>{
Context context;
SyncHttpClient client;
JSONObject response;
public uploadVideoAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
if(client != null){
RequestParams data = new RequestParams();
File video = new File(params[0]);
try {
data.put("upload", video, "video/*");
Log.d("debug", LoginActivity.URL + LoginActivity.URL_UPLOAD_VIDEO);
client.post(LoginActivity.URL+LoginActivity.URL_UPLOAD_VIDEO,data,new JsonHttpResponseHandler(){
#Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
Log.d("debug",bytesWritten +" "+ totalSize);
}
#Override
public void onUserException(Throwable error) {
super.onUserException(error);
Log.d("debug",error.toString());
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d("debug", response.toString());
initializeResponse(response);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.d("debug", errorResponse.toString());
initializeResponse(errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("debug", responseString);
initializeResponse(null);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
initializeResponse(null);
}
}else{
initializeResponse(null);
}
return this.response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
initializeHttpClient();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("debug","ererr");
}
private void initializeResponse(JSONObject response){
this.response = response;
}
private void initializeHttpClient(){
if(client == null){
client = new SyncHttpClient();
//client.setMaxRetriesAndTimeout(LoginActivity.maxRetries, LoginActivity.TIME_OUT);
client.setTimeout(50000);
Log.d("debug", client.getResponseTimeout() + "");
Log.d("debug", client.getConnectTimeout()+"");
client.addHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI1NzFiOTBmOTM4ZmQ1NzA4MGUzMTY1Y2IifQ.2l4DVRTVhxFnD796M5CPIEloGW6N-qBnXxa3lC0XDRU");
//client.addHeader("Content-Type", " application/json");
}
}
}
this code works fine if the file upload takes very less time approx 1 min, But if the file size is greater and take more time . The AsyncHttpclient stops uploading File after some time without any error.
I have already tried with different setTimeOut .
Also there Is no error on server side. with Advanced rest client i have i am able to load any file size.
Thanks
Set
RequestParams data = new RequestParams();
if (file != null && file.exists())
data.put("Db_file", new FileInputStream(file));
data.setForceMultipartEntityContentType(true);
RequestParams class creates a non-buffered ByteArrayEntity to pass to the POST or PUT call, it is very easy to cause OutOfMemory errors with larger files, like when uploading a video or mp3 to a server, which are often larger than 4 or 5 MB.
I have a issue and I need a help. I want to get updates from server via long polling. I'm using this library for server communication. https://github.com/loopj/android-async-http. Here is a code what I'm using
private void connectService() {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.setBasicAuth("key", "");
BaseJsonHttpResponseHandler handler = new BaseJsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
Log.e(TAG, "success body " + rawJsonResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
Log.e(TAG, "error " + throwable.toString());
}
#Override
protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
Log.e(TAG, "response body " + rawJsonData);
return null;
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
Log.e(TAG, "pre progress " + instance.getRequestURI());
}
};
httpClient.get(this, url, null, handler);
}
So I tested in browser and everything is work, but I didn't get any response on my device and also which library you is the best for using long polling?
Thanks
I need some help correcting my approach for using the following API > https://github.com/Privo/PRIVO-Hub/wiki/Web-Services-API-Reference#update-user-display-name.
I am unsure of how to send a JSON object for update using LoopJ AndroidAsyncHttp PUT. I am receiving the following error response
{"message":"Error: null","validationErrors":[]."responseTimestamp":141936124612,"totalCount":-1,"status":"failed","resultCount":-1,"entity":null}
How am I doing this wrong?
AsyncHttpClient client = null;
String authorizationHeader = "token_type", "" + " " + "access_token", "");
client.addHeader("Authorization", authorizationHeader);
client.addHeader("Content-type", "application/json");
client.addHeader("Accept", "application/json");
String requestBody = "displayName=" + "hardcodedDisplayName";
String requestURL = "https://privohub.privo.com/api/" + "account/public/saveDisplayName?" + requestBody;
client.put(requestURL, new ResponseHandler(myClass.this, "displayName", new OnResponseHandler() {
#Override
public void onSuccess(int statusCode, String apiName, JSONObject response) {
if (statusCode == 200) {
Log.i(TAG, "Seems to be working")
}
}
#Override
public void onFailure(int statusCode, String apiName, String responseMessage) {
Log.i(TAG, "Fail: " + responseMessage);
}
#Override
public void onFailure(int statusCode, String apiName, JASONArray errorResponse) {
Log.i(TAG, "Fail: " + errorResponse);
}
#Override
public void onFailure(int statusCode, String apiName, JSONObject errorResponse) {
if (errorResponse != null) {
Log.i(TAG, "Fail: " + errorResponse);
}
}
}));
Looks like you are using AsyncHttpClient,
Use the preparePut and AsyncHttpClient.BoundRequestBuilder builder as in the examples/readme,
AsyncHttpClient client = new AsyncHttpClient(); // not null
// other code here
String requestBody = "displayName=" + "hardcodedDisplayName";
String requestURL = "https://privohub.privo.com/api/" + "account/public/saveDisplayName?" + requestBody;
client.preparePut(requestURL) // sets the urls the put request and gets a AsyncHttpClient.BoundRequestBuilder
.setBody(requestBody) // sets the body of the put request
.execute(new AsyncCompletionHandler<Response>(){
#Override
public Response onCompleted(Response response) throws Exception{
// Do something with the Response
// ...
return response;
}
#Override
public void onThrowable(Throwable t){
// Something wrong happened.
}
});