LoopJ AndroidAsyncHttp - Parameters - Conflict - android

I wanted to import "latest.jason" from "OpenExchange rates" for latest currency rates.
But when I write "AsyncHttpClient" it creates the following "Un-Implemented Class":
#Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
}
But I wanted this- (to run)
public void onSuccess(String arg2) {
Log.i("MYFIRSTAPP" , "HTTP Successs");
try {
JSONObject jsonObj = new JSONObject(arg2);
JSONObject ratesObject = jsonObj.getJSONObject("rates");
Double gbpRate = ratesObject.getDouble("GBP");
Double eurRate = ratesObject.getDouble("EUR");
Log.i("MYFIRSTAPP", "GBP" +gbpRate);
Log.i("MYFIRSTAPP", "EUR" +eurRate);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem I''m getting is:
The onSuccess is taking " int arg0, Header[] arg1, byte[] arg2 " as the parameters...
but i wanted - " String arg2 "

There are many variants of onSuccess and onFailure methods in AsyncHttpResponseHandler and its subclasses.
Most suitable for handling JSON data is in JsonHttpResponseHandler

Try This...
AsyncHttpClient client = new AsyncHttpClient();
client.get(URL, new AsyncHttpResponseHandler()
{
#Override
public void onFailure(int statusCode, Header[] header, byte[] content,
Throwable error)
{
// show error messages here
super.onFailure(statusCode, error, content);
}
#Override
public void onSuccess(int statusCode, Header[] header, byte[] content)
{
if (statusCode == 200)
{
try
{
//convert byte[] to string.
String contentStr = content.toString();
Log.i("Tag", "content" + URL + " " + contentStr );
//String to JSONObject.
JSONObject jsonObj = new JSONObject(contentStr );
JSONObject ratesObject = jsonObj.getJSONObject("rates");
Double gbpRate = ratesObject.getDouble("GBP");
Double eurRate = ratesObject.getDouble("EUR");
Log.i("MYFIRSTAPP", "GBP" + gbpRate);
Log.i("MYFIRSTAPP", "EUR" + eurRate);
}
catch (Exception e)
{
e.toString();
}
}
else
{
// show network error toast here;
}
}
});

Related

GET doesn't enter in methods onSucces and onFailure

I'm trying to do a get with AsyncHttpClient, but doesn't enter in both methods, in Postman it's going well, any idea what could be?
AsyncHttpClient client = new AsyncHttpClient();
String URL = "http://link/link1/link2";
client.get(URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONArray dni;
String strResponseBody = new String(responseBody);
try {
dni = new JSONArray(strResponseBody);
for(int i=0; i < dni.length(); i ++){
dniTemporal = dni.getString(i);
Log.d("DNI : ",""+ dniTemporal );
}
} catch (JSONException e) {
Toast.makeText(JourneyDetails.this, "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("ERROR STATUS:"," "+ statusCode);
}
});

eror when parsing json android no data when run

This is my code how i use to load data with json..
client.get(URL, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
try {
if (!obj.getBoolean("error")) {
JSONArray cest = obj.getJSONArray("list");
String z = "";
if (cest != null) {
int array = cest.length();
mDetail = new ArrayList<OrderItem>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateOrder = new Date();
for (int i = 0; i < array; i++) {
try {
dateOrder = formatter.parse(cest.getJSONObject(i).getString("OrderDate"));
} catch (ParseException e) {}
mDetail.add(new OrderDetailsInfo(UUID.fromString(cest.getJSONObject(i).getString("OrderID"))
, dateOrder,
cest.getJSONObject(i).getString("BrancId"),
cest.getJSONObject(i).getString("DCBranchID"),
cest.getJSONObject(i).getString("OrderDocNo"),
cest.getJSONObject(i).getString("SubdealerID"),
cest.getJSONObject(i).getString("DocOrderNo"),
cest.getJSONObject(i).getString("OrderDocNoAlt"),
cest.getJSONObject(i).getString("SalesChannelID"),
cest.getJSONObject(i).getString("MarketingProgramID"),
cest.getJSONObject(i).getString("MDMarketingProgramID"),
cest.getJSONObject(i).getString("PriceListID")));
}
OrderDetailsAdapter adapter = new OrderDetailsAdapter(getActivity(), mDetail);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), "Refreshed: " + cest.length(), Toast.LENGTH_LONG).show();
} //if (cast != null) {
} //if (!obj.getBoolean("error")) {
} catch (JSONException e) {
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject errorResponse) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
// Probable causes: no internet permission, no internet connection
Toast.makeText(getActivity().getApplicationContext(), "error: onFailure: " + e.toString(), Toast.LENGTH_LONG).show();
}
});
}
When i run this there no eror but the data cannot be load..
What wrong with my code.?
Somebody please help me..

CANNOT POST , can't reach nodejs from android

I can't reach my nodejs server from an androiapp endpoint.
The thing is that I can reach from others post, but not from a new one.
From this url I can reach:
ApiClient.post("/v1/forgot", params,
new AsyncHttpResponseHandler() {
#Override
public void onFailure(int arg0, Header[] arg1,
byte[] arg2, Throwable arg3) {
userMessage=("Password NOT RESET.\n Please check the email entered,\n"+userEmailEntered+"\nor try again later.");
Toast.makeText(getApplicationContext(), userMessage, Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(int arg0, Header[] arg1,
byte[] resp) {
String response = new String(resp);
try {
JSONArray jsonArray=new JSONArray(response);
String json = jsonArray.getJSONObject(0).toString();
final ResetPasswordResponse resetPasswordResponse = JsonUtils.parseJson(json, ResetPasswordResponse.class);
if (resetPasswordResponse.getStatus().equals("sent")){
userMessage=("Reset instructions sent to "+resetPasswordResponse.getEmail());
}else{
userMessage=("The email account entered "+resetPasswordResponse.getEmail()+" is not recognized. Please check the email address entered");
}
Toast.makeText(getApplicationContext(), userMessage, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
But I can't from the new resource and post that Im creating:
Log.i("store", devRegId.toString());
//TODO PROBLEM TO SEND REGISTRATION - cannot post
ApiClient.post("/v1/device", params,new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] resp) {
String response = new String(resp);
Log.i("store", response);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] resp, Throwable error) {
Log.i("store", "NOT ok");
Log.i("store", resp.toString());
String response = new String(resp);
Log.i("store", response);
}
});
And that it`s the client.post created:
private static AsyncHttpClient client = new AsyncHttpClient();
public static void post(String url, RequestParamsCustom params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
Server route:
app.post('/v1/device', function(req,res) {
gcmDeviceRouter.storeDevice(req,res)
});
The server is running ok, I can access from other end point (web app, postman tool).
The error it`s this:
debug I/store﹕ NOT ok
debug I/store﹕ [B#235ae686
debug I/store﹕ Cannot POST /v1/device
Thanks for the help

Long polling issue: No response received

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

LoopJ AndroidAsyncHttp PUT, how to do?

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

Categories

Resources