newman555p
newman555p

Reputation: 181

Update TextView via Async Task

I'm trying to dismiss dialog in AsyncTask's onPostExecute() and also set text in textview, but textview doesn't change and I get the "Window already focused, ignoring focus gain of...".

Here's the code:

    protected void onPreExecute() {
    dialog = ProgressDialog.show(mContext, "","Loading...", true);

}

protected void onPostExecute(Object result) {
    dialog.dismiss();
    tv.setText("some text");

}

Progress dialog is shown and when my background work is complete, it is dismissed but there's no change to textview. Without progress dialog, text view is updated.

Any idea, solution to this problem?

Thanks!

Upvotes: 1

Views: 4514

Answers (2)

Rinkesh
Rinkesh

Reputation: 3316

public class MyActivity extends Activity 
     {
/**
 * Called when the activity is first created.
 */
ProgressBar progressBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    progressBar = (ProgressBar) findViewById(R.id.pb);
    TextView view=(TextView) findViewById(R.id.myt);
    new Task(view).execute();


}

by passing TextView instance in constructor we can use in progressbar

private class Task extends AsyncTask<Void, Integer, Void> {
    TextView view;
    private Task(TextView textView) {
        this.view= textView;
    }

    int myProgress;

    @Override
    protected void onPreExecute() {
        myProgress = 0;
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Toast.makeText(MyActivity.this,
                "onPostExecute", Toast.LENGTH_LONG).show();

        super.onPostExecute(aVoid);
    }

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

        progressBar.setProgress(values[0]);
        view.setText("Value"+myProgress);
        super.onProgressUpdate(values);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();    //To change body of overridden methods use File | Settings | File Templates.
    }


    @Override
    protected Void doInBackground(Void... voids) {
        while (myProgress < 100) {
            myProgress++;

            publishProgress(myProgress);
            SystemClock.sleep(100);
        }
        return null;
    }
}

  }

Upvotes: 0

Swayam
Swayam

Reputation: 16354

Try this code snippet after you have called dialog.dismiss().

         if (!dialog.isShowing()) 
            {
                TextView tv = (TextView) findViewById(R.id.textView);
                tv.setText("some text");
            }

Upvotes: 2

Related Questions