zomlaaa95 zomlaaa95 - 2 months ago 16
Android Question

Android asynctask won't accept context

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

findViewById
, it says that the
findViewById
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

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

private MyActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState){ 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        mTextView = (TextView) findViewById(R.id.textview);
        new MyAsyncTask().execute();
    }

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

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

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

        @Override
        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