Baptiste Faure Baptiste Faure - 6 months ago 19
Java Question

ANDROID : Modification of my layout in real time

I experience some trouble to update my layout in real time on my application.

I would like to show a first screen with a button "Load Data".
When I press the button, I want to change the text to "Loading..." and make a progress bar appear while the app is loading the data. When it's done, I'd like to change again the text to "launch app" and to make disepear the progress bar.

The issue I have is that the text in the button doesn't refrech, and the progressiv bar doesn't show up...

I've tried a lot of things, with and without thread, looking for help on the internet but i couldn't find any suitable tip.

Maybe you have an idea to help me? :D

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
button.setText("Load Data");
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
}

private void appInit() {
try {
((MyApp) getApplication()).getDataFromServer();
} catch (InterruptedException e) {
e.printStackTrace();
}
((MyApp) getApplication()).initData();

}


@Override
public void onClick(final View v) {
Button b = (Button)v;
String buttonText = b.getText().toString();
if(buttonText=="Load Data"){
findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
button.setText("Loading");
appInit();
while(!((MyApp)this.getApplication()).isInitSucceded()){}
button.setText("Launch App");
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
findViewById(R.id.button).setVisibility(View.VISIBLE);
}
else {
Intent intent = new Intent(MainActivity.this, ddcorp.test.Resume.class);
startActivity(intent);
}
}

Answer

Blocking a UI thread with the following line is not a good idea:

while(!((MyApp)this.getApplication()).isInitSucceded()){}

alternatively you can use AsyncTask which has methods for background process, progress update, and post execution logic. Here is an example:

public class MyTask extends AsyncTask<Void,Integer,String>
{
    @override
    public String doInBackground(Void... params)
    {
         //do your background processes
         ...
         publishProgress(someInteger); //for updating progress bar
         ...
         return result;
    }

    @override
    public void onProgressUpdate(Integer... params)
    {
         //do your progress bar update with params[0]
    }

    @override
    public void onPostExecute(String.. params)
    {
         //do something with the results of doInBackground stored in params[0]
    }
}

and here is how to call it:

(new MyTask()).execute();