Android: Android App is not responding, close it? - android

I have an application which sends data to a server and sometimes the following message appears: Android app is not responding , Close it? ( i don't know if is the same in English)
It's difficult to see the log because it happens in one of 20 devices approximately when they are all working, and I can't see the log at that moment.
I think the problem can be with the Asynctask function that sends data to the server.
Here is the function:
class UpdateCandidatos extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Nombres.getPID()));
params.add(new BasicNameValuePair("test", nombre));
params.add(new BasicNameValuePair("pregunta", npregunta));
params.add(new BasicNameValuePair("bateria", levelstring));
params.add(new BasicNameValuePair("correctas", correctasString));
params.add(new BasicNameValuePair("errores", fallosString));
JSONObject json = jsonParser.makeHttpRequest(url_update,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
When it is called the asynctask function:
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
if (radBotA.isChecked()) {
Respuestas[posicion] = "A";
}
else if (radBotB.isChecked()) {
Respuestas[posicion] = "B";
}
else if (radBotC.isChecked()) {
Respuestas[posicion] = "C";
}
else if (radBotD.isChecked()) {
Respuestas[posicion] = "D";
}
else {
Respuestas[posicion] = "";
}
if (Titulacion.IsReachable1(getApplicationContext())) {
Correccion();
new UpdateCandidatos().execute();
}
}
});
The message appears after there is some time that even you click on any button the app continues blocked. Is there anything wrong on my asynctask function? How Could I solve this problem?
Edit: Correccion() is comparing 2 arrays.
public void Correccion(){
correctas = 0;
fallos = 0;
sinresponder = 0;
for(int posicion=0;posicion<=nPreguntas-1;posicion++){
if(Respuestas[posicion].equals(RespuestasC[posicion])){
correctas++;
}
else if(Respuestas[posicion].equals("")){
sinresponder++;
}
else{
fallos++;
}
}
correccion++;
correctasString = String.valueOf(correctas);
fallosString = String.valueOf(fallos);
}
isReachable() is used in order to know if the device can reach the Server.
public static boolean IsReachable1(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
boolean isReachable = false;
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://10.0.0.15/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1 * 200);
urlc.connect();
isReachable = (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e("TAG", e.getMessage());
}
}
return isReachable;
}

If you click several times on the button you start several asyncTask, I suggest:
Avoid multiple task: wait for previous execution end
Use the following code to start the task:
The code:
myTask = new GetDeviceLogTask();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
else
myTask.execute((Void[]) null);
EDIT:
Ok I think you're doing to much things on the main thread that normally is used only to update the user interface and you may not use for caluclations. So try to move Correccion() and .IsReachable1() inside your async task:
class UpdateCandidatos extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
if (!Titulacion.IsReachable1(getApplicationContext())) {
return null;
}
Correccion();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Nombres.getPID()));
params.add(new BasicNameValuePair("test", nombre));
params.add(new BasicNameValuePair("pregunta", npregunta));
params.add(new BasicNameValuePair("bateria", levelstring));
params.add(new BasicNameValuePair("correctas", correctasString));
params.add(new BasicNameValuePair("errores", fallosString));
JSONObject json = jsonParser.makeHttpRequest(url_update,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Related

Database Connection with Json Object Value Null

// I have already jSON file when i called this method its given null value on it.
new load_customername().execute();
Use this method to call below class
public class load_customername extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
//String i = args[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair(TAG_Customer_Name, i));
JSONObject json = jParser.makeHttpRequest(url_get_customername, "GET", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
AsyncTask runs in worker thread, you won't get response instantly. Use onPostExecute with callBack to read the response.

Android Background web service Issue

I really need your help. I am building an Android app that needs a lot of HTTP requests such as logging to the server(check if user is exists or not) and storing the session to the database (user_sessions table), adding, updating and deleting records.
In my Login Activity, I have my AsyncTask (to check if user exits) and other background threads (logs the user session and download user info to database) . This is successful. Next, when I update the user info, it updates successfully. But what if I update using my web app? My should display the newly updated info on my android app. How can I resolve this problem?
This is what I've tried so far:
private void logSessionToServer() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
strUsername = etUsername.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_log_session,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("", "Successfully logged session!");
} else {
// failed
Log.d("", "Not Successful!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
/**
* Background Async Task to Create new record
* */
class LoginTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setIcon(R.drawable.upload);
pDialog.setTitle("Connecting to server");
pDialog.setMessage("Validating login details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
*
* */
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
logSessionToServer(); // Save login to server
saveUserInfoToDB(); // Save user info to DB
saveUserloggedIn(); // Save user logged in to preference
savePriestInfoToDB(); // Save priest to DB
Log.d("", "Successful Login!");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
// failed
new Thread()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(),
"Not Successful Login", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
Log.d("", "Not Successful Login!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private void saveUserInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
map.put(TAG_AGE, jb.getString(TAG_AGE));
map.put(TAG_GENDER, jb.getString(TAG_GENDER));
map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
arraylist.add(map);
String strCusID = jb.getString(TAG_CUS_ID);
String strFname = jb.getString(TAG_FIRSTNAME);
String strMname = jb.getString(TAG_MIDDLENAME);
String strLname = jb.getString(TAG_LASTNAME);
String strEmail = jb.getString(TAG_EMAIL);
String strAge = jb.getString(TAG_AGE);
String strGender = jb.getString(TAG_GENDER);
String strUsername = jb.getString(TAG_USERNAME);
String strPassword = jb.getString(TAG_PASSWORD);
String strBarangay = jb.getString(TAG_BARANGAY);
String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
String strRegDate = jb.getString(TAG_REG_DATE);
String strBDMonth = jb.getString(TAG_BD_MONTH);
String strBDDate = jb.getString(TAG_BD_DATE);
String strBDYear = jb.getString(TAG_BD_YEAR);
try{
dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail,
strAge, strGender, strUsername, strPassword,
strBarangay, strCompleteAddress, strRegDate,
strBDMonth, strBDDate, strBDYear);
Log.d("Response", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
private void savePriestInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_P_ID, jb.getString(TAG_P_ID));
map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
arraylist.add(map);
String strP_ID = jb.getString(TAG_P_ID);
String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
String strP_Lname = jb.getString(TAG_P_LASTNAME);
String strP_Email = jb.getString(TAG_P_EMAIL);
String strP_Age = jb.getString(TAG_P_AGE);
String strP_Address = jb.getString(TAG_P_ADDRESS);
String strP_Status = jb.getString(TAG_P_STATUS);
String strP_Contact = jb.getString(TAG_P_CONTACT);
try{
dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname,
strP_Lname, strP_Email, strP_Age,
strP_Address, strP_Status, strP_Contact);
Log.d("Response - Priest", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response - Priest", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
Feel free to check out my codes and give feedback if this is the best practice for HTTP requests. I am new to Web Services so I really need your help. Any help will be greatly appreciated. Thanks
Well what I just said: you write a thread which downloads user-info every 5 seconds. then it compares the user info downloaded with the user info that is already stored on your device. if there is a difference, an update has been made, and your thread invokes a new download of the updated user info.

I want to send more than one record of sqlite to server

I want to send more than one record of SQLite data to server when my internet connection is come back, i have programmed a broadcast receiver which works when my internet is come back, but it send only one data to server, i want to send all the records of table when internet come back, suggest me that how to pass arguments to async task in for loop, an take each data to params.
public class BroadcastCreateTask extends BroadcastReceiver {
DatabaseHandler db;
public ProgressDialog pDialog;
JSONParser jsonParser=new JSONParser();
private static String url_insert_task= "";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onReceive(Context context, Intent intent) {
db= new DatabaseHandler(context);
boolean status = NetworkUtil.isNetworkAvailable(context);
String s = String.valueOf(status);
if(s.equals("true"))
Toast.makeText(context, "Connected to internet", Toast.LENGTH_LONG).show();
new createTask().execute();
Toast.makeText(context, "data send to server", Toast.LENGTH_SHORT).show();
if(s.equals("false"))
Toast.makeText(context, "Not Connected to internet", Toast.LENGTH_SHORT).show();
}
class createTask extends AsyncTask<String, Void,String>
{
#Override
protected String doInBackground(String... arg0) {
List<Task> tasks = db.getAllContacts();
for(Task t : tasks){
String o = t.getOwner();
String s = t.getSubject();
String st = t.getStartDate();
String dt = t.getDueDate();
String c = t.getContacts();
String sta = t.getStatus();
String p = t.getPriority();
String d = t.getDescription();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("owner",o));
params.add(new BasicNameValuePair("subject",s));
params.add(new BasicNameValuePair("startdate",st));
params.add(new BasicNameValuePair("duedate",dt));
params.add(new BasicNameValuePair("contacts",c));
params.add(new BasicNameValuePair("status",sta));
params.add(new BasicNameValuePair("priority",p));
params.add(new BasicNameValuePair("description",d));
JSONObject json = jsonParser.makeHttpRequest(url_insert_task, "POST", params);
db.deleteContact(new Task(o,s));
// check log cat for response
Log.d("Create Response", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if(success==1)
{
pDialog.dismiss();
}
} catch (JSONException e)
{
// TODO: handle exception
e.printStackTrace();
}
return null;
}
return null;
} // end of background method
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
} // end of async task
}`
You have the statement return null before the closing brace of the for loop. Your loop runs only once and returns, which explains why only one record is being sent.

Android Async doinbackaground data to onpostexecute

I need some help with taking results from doinbackground to onpostexecute. The results are in the form of JSONArray. I want to populate two textviews in the UI through onpostexecute. There is no error in the code but nothing happens as it seems inpostexecute is not getting called. Please help. I have looked at several similar questions here and tried many things but unable to get it to work..thanks in advance. Please note private static final String TAG_LATEST_SCORES = "cricket_scores";
class PostScores extends AsyncTask<JSONArray, Void, JSONArray> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewScoreupdatescricketActivity.this);
pDialog.setMessage("Posting LiveScore Updates..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected JSONArray doInBackground(JSONArray... args) {
String runs1 = runs.getText().toString();
String wicket1 = wicket.getText().toString();
String overs1 = over.getText().toString();
String rr1 = rr.getText().toString();
String team_name = null;
String bat1;
if (innings.isChecked() == false) {
bat1 = "1";
team_name = bat.getText().toString();
} else {
bat1 = "2";
team_name = bat.getText().toString();
}
if (rr1.equals("NA")) {
rr1 = "0";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("runs", runs1));
params.add(new BasicNameValuePair("wickets", wicket1));
params.add(new BasicNameValuePair("id", id1));
params.add(new BasicNameValuePair("overs", overs1));
params.add(new BasicNameValuePair("rr", rr1));
params.add(new BasicNameValuePair("bat", bat1));
params.add(new BasicNameValuePair("team_name", team_name));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
pDialog.dismiss();
if (success == 1) {
latest_scores = json.getJSONArray(TAG_LATEST_SCORES);
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
return latest_scores;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONArray latest_sc) {
// dismiss the dialog once done
try {
for (int i = 0; i < latest_sc.length(); i++) {
JSONObject c = latest_sc.getJSONObject(i);
String wickets = c.getString(TAG_WICKETS);
String runs = c.getString(TAG_RUNS);
score_inngs1.setText(wickets + runs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Check your brackets. After your definition of doInBackground, you have an extra bracket - that one closes off your PostScores class, so your onPostExecute method is defined as a member of whatever class is enclosing PostScores, if any.
Also, you'll need to #Override the AsyncTask methods to provide your own implementation.

How implement ConnectionException -Android

I am communicating with a database in php mysql travez to display results in a ListView, but I'm trying to implement a ExeptionConnection for when 3G or WIFI but the application can not connect, return to previous Activity and show a Toast. but not how to implement it in my code, I could only implement JsonExeption.
This is my code:
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < list_rs.length(); i++) {
JSONObject c = list_rs.getJSONObject(i);
//Process Code
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Where url_list_rs is the url of my php. Where I can Implement ExeptionConnection? Can anyone help? Thank Masters!
If you want to create you own exception, you can do:
//create a new Exception class
public class ConnectionException extends Exception {
public ConnectionException(String message){
super(message);
}
}
In your makeHttpRequest method
if(no connection) { //check connection
throw new ConnectionException ("No connection!");
} else { ... }
Finally, and try-catch block
try {
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
catch(ConnectionException ex) {
ex.printStackTrace();
}
Note: I am not sure if this is the best practice.

Categories

Resources