1

I want to cancel the asyncTask if my result string is null. ( I get a username and password from the user in a login activity and if this username and password don't exist in the database, the asyncTask has to cancel and ready to start the same task.) I read and applied something but they didn't run. Here is my AsyncTask :

class ProductConnect extends AsyncTask<Boolean, String, String> {

   public AsyncResponse delegate=null;

   private Activity activity;


   public void MyAsyncTask(Activity activity) {
        this.activity = activity;
    }


    @Override
    protected String doInBackground(Boolean... params) {

        String result = null;

        StringBuilder sb = new StringBuilder();

        try {

            // http post
            HttpClient httpclient = new DefaultHttpClient();

            HttpGet httppost = new HttpGet( "http://191.165.2.235/getProducts.php?login=1&user_name="+UserName+"&user_pass="+Password);



            HttpResponse response = httpclient.execute(httppost);

            if (response.getStatusLine().getStatusCode() != 200) {
                Log.d("MyApp", "Server encountered an error");
            }

          BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent(), "UTF8"));  



            sb = new StringBuilder();

            sb.append(reader.readLine() + "\n");

            if(reader.readLine() == null){

                asyncTask.cancel(true);
            }

            String line = null;

            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

                if (isCancelled()) break;
            }


            result = sb.toString();

            Log.d("test", result);

        } 
        catch (Exception e) {

            Log.e("log_tag", "Error converting result " + e.toString());

        }

        return result;
    }




    @Override
    protected void onPostExecute(String result) {

        Intent passValue=new Intent(MainActivity.this, second.class);



        try {

            JSONArray jArray = new JSONArray(result);
            JSONObject json_data;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);

                t = json_data.getString("name");
                names.add(t);                                             

                latitude=json_data.getString("lat");
                lats.add(latitude);                                       

                longtitude=json_data.getString("lon");
                longts.add(longtitude);                                   

            }


            passValue.putStringArrayListExtra("latitudes", (ArrayList<String>) lats);

            passValue.putStringArrayListExtra("veri", (ArrayList<String>) names);

            passValue.putStringArrayListExtra("longtitudes", (ArrayList<String>) longts);

            startActivity(passValue);   

        } catch (JSONException e1) {
            e1.printStackTrace();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        super.onPostExecute(result);
    }

     protected void onPreExecute()                          {
            super.onPreExecute();
            ProgressDialog pd = new ProgressDialog(MainActivity.this);
            pd.setTitle("Lütfen Bekleyiniz");
            pd.setMessage("Authenticating..");
            pd.show();

                                                                     }
}

How should i follow a way ? Which methods should i use?

elfoz
  • 115
  • 1
  • 8
  • 17

3 Answers3

0

You are missing logic here, you should only call Async task if your data is not null. Like this

b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            EditText username=(EditText)findViewById(R.id.editText2);

            String UserName=username.getText().toString().trim();

            EditText password=(EditText)findViewById(R.id.editText1);
            String Password=password.getText().toString().trim(); 

            if (UserName.length()>0&& Password.length()>0) {
                asyncTask.execute(true); } 
        }
    });
Jitender Dev
  • 6,907
  • 2
  • 24
  • 35
  • 1
    It didn't work and I also want to check if the string of fetching data is null so that have to do i in background or onpostexecute? – elfoz Oct 09 '13 at 09:19
  • The database connection is started when the button click in onCreate. and I tried: b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub username=(EditText)findViewById(R.id.editText2); UserName=username.getText().toString(); password=(EditText)findViewById(R.id.editText1); Password=password.getText().toString(); if (UserName!=null&& Password!=null) { asyncTask.execute(true); } – elfoz Oct 09 '13 at 09:32
  • Updated answer, check now – Jitender Dev Oct 09 '13 at 10:22
  • It works for if the user doesn't enter some values. thank you but i have to do also fecth the username and password and check them with entering values. If this user and password don't exist in the database , thread cancel and ready to start new one. – elfoz Oct 09 '13 at 11:07
0

AsyncTask is mainly using for operations which we wants to do in background thread, like webservice call. In this scenario, you are using AsyncTask for saving username and password through webservice. So before executing AsyncTask you must validate and have a null-check for both edit-texts for username and password. If everything is fine and get the password according to the defined password policy, just invoke the AsyncTask with these two values for httppost.

  • I told my problem by wrong way so i updated my question explanation. I take the username and password from the user then I checked them in the database. If this username and password don't exist in the database, the AsyncTask should stop, don't start second activity and a new AsyncTask has to ready to start in login page. I'm confused about that what can i do this in my posting code? – elfoz Oct 09 '13 at 11:13
  • So it is better to write two AsyncTask. One for checking the availability of username (password could be same) and second for pushing value in to db. Start the second AsyncTask from onPostExecute() of first one. – Manesh Appukuttan Oct 09 '13 at 12:24
  • Can i solve this issue with one AsyncTask. Is it impossible exactly? – elfoz Oct 09 '13 at 12:28
  • I think this will do perfectly and you can check the availability of username while editing the edit text for username. After the check, if username is acceptable, you can enable the edittext for password. After clicking the submit button, can call the second Asynctask. – Manesh Appukuttan Oct 09 '13 at 12:35
  • Pls check dis..http://stackoverflow.com/questions/4494241/android-ajax-style-auto-check-of-username-availability – Manesh Appukuttan Oct 09 '13 at 12:37
  • Could The same task start again after cancel or stop? – elfoz Oct 09 '13 at 14:29
  • Dont allow the second AsyncTask to run on Cancel/Stop button click on Login screen. – Manesh Appukuttan Oct 10 '13 at 09:01
0

I notice this old post does not have the answer. So I will post this, hopefully it will help others.

To cancel a task simply call cancel()

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Parameters mayInterruptIfRunning true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.

Returns false if the task could not be cancelled, typically because it has already completed normally; true otherwise


So in your case:

result = sb.toString();

if(result==null){
   this.cancel(true);
}
Log.d("test", result);

to cancel outside of the task:

myTask.cancel(true);

You can use isCancel() to check , it returns true if this task was cancelled before it completed normally.

Additonally you can override asynctask method onCancelled() to take action when it's cancelled.

@Override
protected void onCancelled() {

}
meda
  • 45,103
  • 14
  • 92
  • 122