0

I'm beginner in Android Devloping, I have a trouble with UI in Android

I have a code look like this:

public class MainActivity extends Activity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv1 = (TextView) findViewById(R.id.textView1);
        TextView tv2 = (TextView) findViewById(R.id.textView2);

        tv1.setVisibility(View.GONE);
        tv2.setVisibility(View.GONE);

        String s="abc";
        MyAsyncTask BkGroundTask = new MyAsyncTask(); 
        BkGroundTask.execute(s);
        try {
            s = BkGroundTask.get();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();}

        tv1.setVisibility(View.VISIBLE);
        tv2.setVisibility(View.VISIBLE);

    }
}

But tv1 and tv2 do not disappear when AsyncTask is running. What should I do to fix this?

Kalel Wade
  • 7,742
  • 3
  • 39
  • 55
teo ten
  • 79
  • 1
  • 2
  • i don't see the Async task here but i think you should make the text views disappear either in the onPreExecute or onPostExecute methods in your Async Task,since this methods have access to the UI http://developer.android.com/reference/android/os/AsyncTask.html – danidee Sep 25 '14 at 16:55

2 Answers2

0

This has been discussed many times but I will explain again for what you want since you want a special scenario...

You almost never want to use .get() because it is a blocking call. This means that it will lock up your UI until the task is finished. .execute(), as you have, is what you want.

If you want them to be gone while the task is running and be visible again when the task finishes then you want to put the code to show them inside of onPostExecute() if it is an inner-class and if not then you can use a callback to the Activity from onPostExecute() and show them in the callback method.

This answer discusses how to use an interface with your AsyncTask

Related Post

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
0

an asynctask executes asynchronously, you are on the assumption that everything pauses when you call execute which is wrong and would defeat the purpose of an asynctask. in reality it is disappearing but then reappearing. it is happening so fast that you probably cant even notice it.

if you want to textview to display when the task is done you need to do that in the onpostexecute of the task

example

@Override
public void onPostExecute(Void void){
    tv1.setVisibility(View.VISIBLE);
    tv2.setVisibility(View.VISIBLE);
}
tyczj
  • 71,600
  • 54
  • 194
  • 296