ali
ali

Reputation: 11045

Make a TextView visible when AsyncTask starts

I want my AsyncTask class to change the visibility of a TextView from my layout and I get a fatal error. If I want to get the text value of the TextView, it works fine, but when trying to set the visibility it just crashes.

// Main Activity (MainActivity.java)
Context MainContext= getApplicationContext();
new MyAsyncTask((TextView)findViewById(R.id.my_text_view)).execute();

// My Async Task (MyAsyncTask.java)
public class MyAsyncTask extends AsyncTask <String, Void, String> {
    private Context context;
private TextView my_text_view;

public MyAsyncTask (TextView my_text_view){
        this.context = MainActivity.MainContext;
    this.txt_loading = my_text_view;
}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    my_text_view.setVisibility(View.VISIBLE); // crashes
    Log.i("Value: ", String.valueOf(this.my_text_view.getText())); // O.K.!
    return null;
}

@Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onProgressUpdate(Void... values) {

    }

}

How can I make it work? Also, can I get the TextView from the Context? I don't want to send it as a parameter to the constructor.

Upvotes: 0

Views: 1351

Answers (1)

Simon Dorociak
Simon Dorociak

Reputation: 33505

It crashes because you are manipuling with UI in background Thread. This is not allowed and you can't do it.

my_text_view.setVisibility(View.VISIBLE);

User Interface may be updated / changed only from original / main / UI Thread. AsyncTask provides some methods that actually runs on UI Thread.

These methods are exactly designated for reach your goal: to perform any UI update.

When you want to update UI from AsyncTask, you can use:

  • onPreExecute()
  • onProgressUpdate()
  • onPostExecute()

Upvotes: 5

Related Questions