tj walker
tj walker

Reputation: 1343

Android AsyncTask Instance or class

I am making a program that when the user clicks the button the asynctask is called in onclick. But everytime the user clicks the button the text changes... How can i implement something that i can call just to utilize the async method.

Here is a example of what i mean

public void Talk(){     

   text1.setText("Welcome what is your name?");

   respond.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
         name = edit.getText().toString();

         new AsyncTask<Void, Integer, Void>(){
            @Override
            protected Void doInBackground(Void... arg0) {
               try {                 
                  Thread.sleep(850);             
               } catch (InterruptedException e) {                         
                  e.printStackTrace();             
               }            

               return null;
            }

            @Override         
            protected void onPostExecute(Void result) {             
               text1.setText("Nice to meet you "+name);
               dismissDialog(typeBar);
            }

            @Override        
            protected void onPreExecute() { 
               typeBar = 0;
               showDialog(typeBar);
            }       
         }.execute((Void)null);     
      }
   });
}

So as you can see evertime the user presses the button the text changes. It will definitely be to tedious to type the ayncTask method EVERYTIME the button is clicked. Anyone know a way i could do this?

Upvotes: 1

Views: 2845

Answers (1)

Lukas Batteau
Lukas Batteau

Reputation: 2483

I'll just ignore why you're using an AsyncTask for whatever you're doing. Don't use an inline class. Create a private class within your Activity:

 private class MyAsyncTask extends AsyncTask<String, Void, Void> 

And reuse it, e.g.:

MyAsyncTask.execute("Whatever")

Upvotes: 1

Related Questions