eror when parsing json android no data when run - android

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

Related

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
}

could not sending data to server using on success function in android studio

i am trying to send data from sqlite database to server but i am getting the error on the on failure function that cannot connect to the internet.while my internet is connected.
public void syncSQLiteMySQLDB(){
//Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
if(userList.size()!=0){
Toast.makeText(getApplicationContext(),"synchingi",Toast.LENGTH_LONG).show();
if (controller.dbSyncCount() != 0) {
prgDialog.show();
Toast.makeText(getApplicationContext(),"posting",Toast.LENGTH_LONG).show();
params.put("usersJSON", controller.composeJSONfromSQLite());
client.post("http://10.0.2.2/insertuser.php", params, new AsyncHttpResponseHandler() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int status, Header[] headers, byte[] response) {
Toast.makeText(getApplicationContext(),"on success function",Toast.LENGTH_LONG).show();
System.out.println(response);
prgDialog.hide();
try {
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("status"));
controller.updateSyncStatus(obj.get("id").toString(), obj.get("status").toString());
}
Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
} 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, byte[] content, Throwable error) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
}
}

AndroidHttpAsync not working at oncreate method

Whenever I use AsyncHttpClient in onCreate(Bundle savedInstanceState), onSuccess() method never used.
I put a break point, than debug... Never visit to break point if the break point is in the onSuccess() method, but when I put a button, after button click, it works?
I need to get values in onCreate() methods...
String url = "http://192.168.56.1:8080/restfulwssample/rest/examples/wsetkinlikgetir/";
url = url + eposta;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonobject = arr.getJSONObject(i);
String ali = jsonobject.getString("etkinlikAdi");
etkinlikAdlari[i] = jsonobject.getString("etkinlikTarihi");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404", Toast.LENGTH_LONG);
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500", Toast.LENGTH_LONG);
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Else", Toast.LENGTH_LONG);
}
}
});
Of course, i can share my activity code
public class TestActivity extends Activity{
JSONArray arr = null;
String[] etkinlikAdlari;
String eposta;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down_temp);
String url = "http://192.168.56.1:8080/restfulwssample/rest/examples/wsetkinlikgetir/";
url = url + eposta;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonobject = arr.getJSONObject(i);
String ali = jsonobject.getString("etkinlikAdi");
etkinlikAdlari[i] = jsonobject.getString("etkinlikTarihi");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404", Toast.LENGTH_LONG);
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500", Toast.LENGTH_LONG);
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Else", Toast.LENGTH_LONG);
}
}
});
}
}

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

LoopJ AndroidAsyncHttp - Parameters - Conflict

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

Categories

Resources