/*Here you can see an example of asynctask that updates a progress bar and add a coma to some string and post the text on a TextView
*/
package asctask.mig;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class AscTaskActivity extends Activity {
TextView tv1;
String st,st1,st2,st3;
ProgressBar pb1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
st = "";
TextView tv1 = (TextView) findViewById(R.id.tv1);
atask task = new atask();
String st1 = "um", st2 = "dois", st3 = "Tres";
task.execute(st1, st2, st3);
}
private class atask extends AsyncTask<String, Integer, String> {
// can use UI thread here
protected void onPreExecute(String st) {
st1=st1+"1";
st2=st2+"2";
st3=st3+"3";
Toast.makeText(getApplicationContext(), st1+st2+st3,1).show();
}
protected void onProgressUpdate(Integer... p){
pb1=(ProgressBar)findViewById(R.id.pb1);
pb1.setProgress(p[0]);
}
// automatically done on worker thread (separate from UI thread)
@Override
protected String doInBackground(String... in) {
String fixed = "";
int z;
for (z=1;z<100;z++){
try {
Thread.sleep(100);
publishProgress(z);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (z = 0; z < in.length; z++) {//Processa dados recebidos
fixed+= in[z]+ ";";
}
return fixed; //retorna dados processados
}
// can use UI thread here
protected void onPostExecute(String st) {
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText(st);
}
}
}
Share