Moudiz Moudiz - 1 year ago 83
Android Question

how to stop asyncatask from executing while checking not null in onpreexecute

I have this asynctask thats it working fine , however I want to check in

if the Edit text are empty or not before doing anything. this line
is wrong I dont want edit text to be empty before connecting to server.

my other problem i want to add the alert dialog in
to tell the user to fill the empty edit text but
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LoginActivity.this);
it will not be accessed in doInBackground , the image shows that its not being used but
exists in
how to make them access also there ?
enter image description here

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
protected void onPreExecute()
name = usernam.getText().toString();
pass = passw.getText().toString();
//emails = email.getText().toString();
if (name = null || pass =null)
close(); // i guess this is wrong i want to stop the asynctask

protected String doInBackground(String... params) {
//doing connections to the server

final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LoginActivity.this);
alertDialogBuilder.setMessage("Wrong username or password, Try again please.");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(MainActivity.this,"You clicked yes button",Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, LoginActivity.class);

Answer Source

Firstly, name and pass will never be null where you are testing them (though they might be empty strings).

You cannot stop the AsyncTask once started - If you don't want the task executed, check the fields before you start the AsyncTask. If you must perform a test inside onPreExecute, just set a field to return from doInBackground() if you don't want it to do anything.

Lastly, you should show the AlertDialog in onPostExecute().

Something like this would be better:

void checkCredentials() {
   String name = usernam.getText().toString();
   String pass = passw.getText().toString();
          //emails = email.getText().toString();
   if (name.equals("") || pass.equals(""))
      new SendPostReqAsyncTask().execute(name,pass);

void showWrongCredentials() {

class SendPostReqAsyncTask extends AsyncTask<String, Void, Boolean> {
        protected Boolean doInBackground(String... params) {
           String name = params[0];
           String pass = params[1];
           //doing connections to the server 
           // return true/false;

       protected void onPostExecute(Boolean ok) {
           if (!ok)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download