why AsyncHttpClient method calls both onSuccess and onFailure method simultaneously - android

I don't understand why both the methods are called simultaneously ie onSuccess and onFailure method of AsyncHttpClient. Here is the following code snippet.
AsyncHttpClient client = new AsyncHttpClient();
client.post(context, url, entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj)
{
System.out.print("Inside success method....");
try
{
System.out.println("Inside try of success method");
if ("SUCCESS".equals(obj.getString("status")))
{
System.out.println("Status : " + obj.getString("status"));
statusFlag = statusFlag+1;
System.out.println("Double Status Flag: "+statusFlag);
}
else
{
//statusFlag = 2;
}
}
catch (JSONException e)
{
//statusFlag = 3;
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
{
if (statusCode == 404)
{
//statusFlag = 4;
}
else if (statusCode == 500)
{
//statusFlag = 5;
}
else
{
//statusFlag = 6;
}
}
});

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

How to read data from Realm

I develop my login application using Realm.
I write in Realm my token in line 'Config myConfig = mRealm.createObject(Config.class)'. Afterwards reading from Realm gives no result likewise Realm has no entries.
I do check in this piece of code that I tagged as '//check - why no users here'.
And User.size() equals to zero.
public class MainActivity extends AppCompatActivity {
private Realm mRealm;
private Realm mRealmInstance;
Button btnLogin;
public void onLogin() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.add("email", "name#example.com");
rp.add("password", "159753");
RequestHandle post = client.post("https://example.com/api/v1/auth", rp, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// Root JSON in response is an dictionary i.e { "data : [ ... ] }
// Handle resulting parsed JSON response here
try {
String tokenString = response.getString("token");
mRealm.beginTransaction();
Config myConfig = mRealm.createObject(Config.class);
myConfig.name = "token";
myConfig.tokenValue = tokenString;
mRealm.commitTransaction();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
//check - why no users here
TextView tvHello = (TextView)findViewById(R.id.tvHello);
try {
RealmResults User = mRealmInstance.where(Config.class).equalTo("name", "token").findAllAsync();
if (User.size() > 0) {
String nameOfUser = User.get(0).toString();
tvHello.setText(nameOfUser);
} else if (User.size() == 0) {
Log.e("query","query size is "+User.size());
}
} catch (Exception e) {
e.printStackTrace();
}
//end of test block
}
You're doing an asynchronous network call before accessing your data. The network call has not completed yet, therefore your data is empty. Put your data access code in the onSuccess() callback.
public class MainActivity extends AppCompatActivity {
...
public void onLogin() {
...
RequestHandle post = client.post(
"https://example.com/api/v1/auth",
rp,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(
int statusCode,
Header[] headers,
JSONObject response) {
try {
String tokenString = response.getString("token");
mRealm.beginTransaction();
Config myConfig = mRealm.createObject(Config.class);
myConfig.name = "token";
myConfig.tokenValue = tokenString;
mRealm.commitTransaction();
populateData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(
int statusCode,
Header[] headers,
String res,
Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
}
private void populateData() {
TextView tvHello = (TextView)findViewById(R.id.tvHello);
try {
RealmResults User =
mRealmInstance.where(Config.class).equalTo("name", "token").findAll();
if (User.size() > 0) {
String nameOfUser = User.get(0).toString();
tvHello.setText(nameOfUser);
} else if (User.size() == 0) {
Log.e("query","query size is "+User.size());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Also note that you should use findAll() instead of findAllAsync(). Read the documentation for more information on the difference: https://realm.io/blog/realm-java-0-84-0/
This is because client.post(... will be executed in another thread. Only after that task is completed onSuccess()will be executed in the UI thread. The code after //check - why no users here is executed before or while onSuccess() is executing. That is why User.size() equals to zero. Modify your code to get it working
public class MainActivity extends AppCompatActivity {
private Realm mRealm;
private Realm mRealmInstance;
private TextView tvHello;
Button btnLogin;
public void onLogin() {
tvHello = (TextView) findViewById(R.id.tvHello);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.add("email", "name#example.com");
rp.add("password", "159753");
RequestHandle post = client.post("https://example.com/api/v1/auth", rp, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// Root JSON in response is an dictionary i.e { "data : [ ... ] }
// Handle resulting parsed JSON response here
try {
String tokenString = response.getString("token");
mRealm.beginTransaction();
Config myConfig = mRealm.createObject(Config.class);
myConfig.name = "token";
myConfig.tokenValue = tokenString;
mRealm.commitTransaction();
RealmResults User = mRealmInstance.where(Config.class).equalTo("name", "token").findAllAsync();
if (User.size() > 0) {
String nameOfUser = User.get(0).toString();
tvHello.setText(nameOfUser);
} else if (User.size() == 0) {
Log.e("query", "query size is " + User.size());
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
}
}
To receive notifications when the Realm was written to from a background thread, you should use a RealmChangeListener (and keep the RealmResults as a field).
public class MainActivity extends AppCompatActivity {
private Realm realm;
Button btnLogin;
private RealmResults<Config> userResults;
private RealmChangeListener<RealmResults<Config>> changeListener = new RealmChangeListener<RealmResults<Config>>() {
#Override
public void onChange(RealmResults<Config> element) {
TextView tvHello = (TextView)findViewById(R.id.tvHello);
try {
if (element.size() > 0) {
String nameOfUser = element.get(0).toString();
tvHello.setText(nameOfUser);
} else if (element.size() == 0) {
Log.e("query","query size is "+element.size());
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(..);
realm = Realm.getDefaultInstance();
userResults = realm.where(Config.class).equalTo("name", "token").findAllAsync();
userResults.addChangeListener(changeListener);
}
#Override
public void onDestroy() {
super.onDestroy();
userResults.removeAllChangeListeners();
userResults = null;
realm.close();
realm = null;
}
public void onLogin() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.add("email", "name#example.com");
rp.add("password", "159753");
RequestHandle post = client.post("https://example.com/api/v1/auth", rp, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// Root JSON in response is an dictionary i.e { "data : [ ... ] }
// Handle resulting parsed JSON response here
try {
String tokenString = response.getString("token");
try(Realm r = Realm.getDefaultInstance()) {
r.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Config myConfig = realm.createObject(Config.class);
myConfig.name = "token";
myConfig.tokenValue = tokenString;
}
});
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
//end of test block
}

Non English text are converting into junk values

In my project am working on json to receive and send response to a server. Its working fine for English letters.
Now the problem is when am used non English letters(Telugu,Tamil, or Hindi) are automatically converted into junk values(??????????) in sever side database.
Sample method calling server:
AsyncHttpClient mNewCaller = new AsyncHttpClient();
mNewCaller.setTimeout(DEFAULT_TIMEOUT);
final ProgressDialog mpd = new ProgressDialog(mContext);
mpd.setTitle("Please wait");
mpd.setMessage("Signing in");
mpd.setCancelable(false);
RequestParams mParams = new RequestParams();
mParams.add(Constants.JSON_HEADER, obj1.toString());
mParams.add(Constants.JSON_BODY, obj2.toString());
// Pref.setValue(getApplicationContext(), Constants.PREF_IMEIID, uid);
Log.e("login", mParams.toString());
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View promptView = layoutInflater.inflate(R.layout.device_name, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setView(promptView);
final EditText code = (EditText) promptView.findViewById(R.id.deviceName);
alertDialogBuilder.setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
authCode = code.getText().toString();
sendDName(authCode, mContext);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertD = alertDialogBuilder.create();
Constants.EMAIL_ID = email;
String url = DynamicURL;
mNewCaller.get(Login.DynamicURL, mParams, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
if (mpd != null) {
mpd.show();
}
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e("frag", responseString + " " + statusCode);
if (mpd != null) {
mpd.dismiss();
}
if (responseString.equalsIgnoreCase("NODEVICENAME")) {
alertD.show();
}
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Constants.EMAIL_ID = email;
Log.e("frag", response.toString() + " " + statusCode);
JSONArray jAry = null;
if (mpd != null) {
mpd.dismiss();
}
if (response.has(Constants.STATUS)) {
try {
if (response.getString(Constants.STATUS).equalsIgnoreCase("TABLOGINFAILED")) {
Snack.show(mContext, "Wrong email or password");
// Toast.makeText(getApplicationContext(), "Wrong email or password", Toast.LENGTH_LONG).show();
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (response.getString(Constants.STATUS).equalsIgnoreCase("NODEVICENAME")) {
alertD.show();
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
Constants.DEVICE_NAME = response.getString(Constants.DEVICENAME);
Constants.CUSTOMER_ID = response.getString("customerid");
jAry = response.getJSONArray(Constants.CAMPAIGN_LIST);
if (response.has("otpenabled")) {
Constants.OTP_ENABLED = response.getBoolean("otpenabled");
Constants.OTP_ENABLED = false;
}
Constants.PREF_JSONARRAY = jAry.toString();
} catch (JSONException e) {
e.printStackTrace();
}
Constants.login = 1;
intent = new Intent(Login.this, Home.class);
startActivity(intent);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("frag", response.toString() + " " + statusCode);
if (mpd != null) {
mpd.dismiss();
}
Log.e("frag", response.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("frag", responseString + " " + statusCode);
if (statusCode == 500) {
// Snack.show(mContext, "Please try again with a valid email id");
new SweetAlertDialog(Login.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("User does not exist")
.setContentText("Please try again with a valid email id")
.show();
}
if (mpd != null) {
mpd.dismiss();
}
/*if (responseString.equalsIgnoreCase("FALSE")) {
alertD.show();
}*/
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("frag", statusCode + " failed obj");
try {
if (statusCode == 0) {
new SweetAlertDialog(Login.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Server Down")
.setContentText("Please try again later")
.show();
} else if (errorResponse.getString(Constants.STATUS).equalsIgnoreCase("NODEVICENAME")) {
alertD.show();
return;
} else if (errorResponse.getString(Constants.STATUS).equalsIgnoreCase("TABLOGINFAILED")) {
// Snack.show(mContext, "Please check your email or password");
new SweetAlertDialog(Login.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Incorrect login details")
.setContentText("Please check your email or password")
.show();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
// Snack.show(mContext, "Wrong email or password");
if (mpd != null) {
mpd.dismiss();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray
errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("frag", errorResponse.toString() + " " + statusCode);
Snack.show(mContext, "Wrong email or password");
if (mpd != null) {
mpd.dismiss();
}
}
});

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..

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