Er_
Er_

Reputation: 23

Check connection on AsyncTask

I check the connection and the correct link before the asynctask, but sometimes the application crash, for do it on the UI thread i think. If i put the code on the AsyncTask the application always crash. Any solution?

On the onCreate method:

if(connectionOK())
      {
          try {
                url = new URL(bundle.getString("direccion"));
                con = (HttpURLConnection) url.openConnection();
                if(con.getResponseCode() == HttpURLConnection.HTTP_OK)
                {
                    Tarea tarea = new Tarea(this);
                    tarea.execute();
                }
                else
                {
                    con.disconnect();
                   //show alertdialog with the problem
                    direccionInvalida();
                }
        } catch (Exception e){e.printStackTrace();}

      }
      else
      { 
             //show alertdialog with the problem
             notConnection() 
      }

Upvotes: 0

Views: 155

Answers (2)

MuraliGanesan
MuraliGanesan

Reputation: 3261

Try this, check net connection inside doInBackground.

public class GetTask extends AsyncTask<Void, Void, Integer> {

    protected void onPreExecute() {
        mProgressDialog = ProgressDialog.show(MainActivity.this,
                "Loading", "Please wait");
    }

    @Override
    protected Integer doInBackground(Void... params) {
        // TODO Auto-generated method stub
                   if(connectionOK()){
        //ADD YOUR API CALL
              return 0;
                  }esle{
                     return 1;
                   }

    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        } 
                    if(result == 0){
                       //do your stuff
                     }else{
                      //show alertdialog with the problem
                     }

    }
}

Upvotes: 1

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

Your question is very vague!

Yet: In newer androids, you can not execute this line on the UI thread:

con = (HttpURLConnection) url.openConnection();

so a simple solution would be to add everything inside a new Thread:

new Thread() {
    public void run() {
        //add all your code
    }
}.start();

However, your code has some blocks to show a dialog (guessing) like this:

//show alertdialog with the problem
notConnection();

These function should be done on the UI thread. So use a handler:

//add this outsire the thread
Handler mHandler = new Handler();

Then inside your code use:

mHandler.post(new Runnable() {
    public void run() {
        notConnection();
    }
});

Finally, this is a fix. The real solution would be for you to post the AsyncTask anyway and handle errors or success in the onPostExecute()

Upvotes: 0

Related Questions