zomlaaa95 zomlaaa95 - 1 year ago 74
Android Question

Android asynctask won't accept context

I have a strange problem. I am trying to change a TextView but cannot

, it says that the
cannot be resolved. I have a Main Activity from which I am calling
AsyncTask(Context context)
. In the constructor I pass this from main activity, I have already tried with Main Activity.getContext() but it still doesn't work.

Any help is welcome.

public class UcitavanjeUpozadini extends AsyncTask<Void, Void, Void> {

private Context context;
private ProgressDialog progressDialog;
private UcitavanjeHelperKlasa helperKlasa;
private List<OglasHelper> lista;

public UcitavanjeUpozadini(Context context){
this.context = context;
this.progressDialog = null;
this.helperKlasa = new UcitavanjeHelperKlasa();
this.lista = new ArrayList<OglasHelper>();


Mat Mat
Answer Source

You should do something like this if you have an activity, change the TextView value in onPostExecute:

private MyActivity extends AppCompatActivity {

    private TextView mTextView;

    protected void onCreate(Bundle savedInstanceState){ 
        mTextView = (TextView) findViewById(R.id.textview);
        new MyAsyncTask().execute();

    private class MyAsyncTask extends AsyncTask<Void, Void, Boolean>{

        protected void onPreExecute(){
            mTextView.setText("text changed before background operation");

        protected Boolean doInBackground(Void... params){
            //perform your background operations changing the paramaters 
            //and return type accordingly
            return true;

        protected void onPostExecute(Boolean result){
            mTextView.setText("text changed after background operation");

If you need to put the AsyncTask in a separate file, you could add a callback to an interface implemented in your Activity or pass the TextView to the AsyncTask during the instantiation