Non English text are converting into junk values - android

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

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
}

why AsyncHttpClient method calls both onSuccess and onFailure method simultaneously

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

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

Send JSON as a POST request to server by AsyncHttpClient

I want to send JSON as a POST to my localhost server with LoopJ's AsndroidAsyncHttpt. I'm using this method:
public void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler)
in my code but it doesn't work. Here is my code:
private void loginUser() throws JSONException, UnsupportedEncodingException {
String login = textLogin.getText().toString();
String password = textPassword.getText().toString();
JSONObject jsonObject = new JSONObject();
if(Utility.isNotNull(login) && Utility.isNotNull(password)) {
jsonObject.put("username", login);
jsonObject.put("password", password);
invokeWS(jsonObject);
}
else{
Toast.makeText(getApplicationContext(), "Proszę wypełnić wszystkie pola!", Toast.LENGTH_LONG).show();
}
}
private void invokeWS(JSONObject jsonObject) throws UnsupportedEncodingException {
StringEntity entity = new StringEntity(jsonObject.toString());
AsyncHttpClient client = new AsyncHttpClient();
Log.i("SER", "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth" + entity);
Log.i("SER", "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth" + jsonObject);
client.post(getApplicationContext(), "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
try {
Log.i("SER", "HERE!");
String login = obj.getString("login");
int ID = obj.getInt("id");
//user.setUserId(obj.getInt("userid"));
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404 - Nie odnaleziono serwera!", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500 - Coś poszło nie tak po stronie serwera!", Toast.LENGTH_LONG).show();
} else if (statusCode == 403) {
Toast.makeText(getApplicationContext(), "Podano niepoprawne dane!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), throwable.toString(), Toast.LENGTH_LONG).show();
}
}
});
}
My Logs looks ok:
http://MY_IP_ADDRESS:8080/silownia_java/rest/login/authorg.apache.http.entity.StringEntity#384d6a6d
http://MY_IP_ADDRESS:8080/silownia_java/rest/login/auth{"username":"barni","password":"12345"}
But i get such error:
org.apache.http.client.HttpResponseException: Unsupported Media Type
Additionaly, I know that server doesn't get any request. So, what the cause could be?
I solved it, by adding header information to my entity object.
ByteArrayEntity entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

Categories

Resources