hi guy
m using a asynctask for running a progressbar. i am using it for showing my songs duration.i want that when i press stop Button, the asynctask should be stop and progressbar should reach on initial position.
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AudioPlayer2.this,
"onPostExecute", Toast.LENGTH_LONG).show();
seekbar.setClickable(true);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AudioPlayer2.this,
"onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
//seekbar.setProgress(myProgress);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
//seekbar.setProgress(myProgress);
publishProgress(myProgress);
Log.d("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA", bundleDuration);
SystemClock.sleep(2000) ;
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
// myProgress=0;
// seekbar.
publishProgress(0);
seekbar.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
seekbar.setProgress(values[0]);
}
}
//=====================================
for starting and stopping m using this code
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
new BackgroundAsyncTask().execute();
break;
case R.id.buttonStop:
backgrondasynctask.cancel(true);
break;
I think you use wrong method for this example. You can easily implement progress bar. Here is a nice article,http://blog.sptechnolab.com/2011/01/17/android/simple-progress-bar-in-android-using-thread/ contains example to implement progress bar. Through this example you can easily start, stop and play the progress bar.
Related
I'm going to create a flash light program. it works with progress bar change as user input for setting sleep function value to Blinking flash light. wen i call my AsyncTask from SeekBarChangeListener it does not work and nothing happen. but when i call it from onCreate function or other classes, every thing is OK and work correctly.
My SeekBarChangeListener:
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
Blinker bbb = new Blinker();
seekBarValue.setText(String.valueOf(progress));
try {
bbb.execute(progress*100);
} catch(Exception e) {
System.out.println("got interrupted!");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
My AsyncTask:
public final class Blinker extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
try {
while (isFlashing)
{
turnOffFlashing();
Thread.sleep(params[0]);
turnOnFlashing();
Thread.sleep(params[0]);
if (isCancelled()) break;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
If you have any idea to make it works please share with me. Thank you.
I am trying to make a simple AsynTask sample. I can't make it run. When I click the Button, ProgressDialog is supposed to be displayed. But nothing happens. I don't get any Exceptions. Probably I'm missing out a few things.
ProgressDialog dialog=null;
Button btnstart;
MyAsynTask mytask;
static final int SLEEP_TIME=(15*1000)/100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=(Button)findViewById(R.id.button1);
btnstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mytask=new MyAsynTask();
mytask.execute();
}
});
}
public class MyAsynTask extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
if(isCancelled()){
break;
}
else {
publishProgress(i);
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
You are doing it right.
Use Logs in onPreExecute(),doInBackBackground() to see what's happening actually.
Add one more method to Asynctask class
onPostExcute()
{
dialog.dismiss();
}
OnPost method in the asynctask excutes after doinbackgournd method there you need to dismiss the dialog
In my application when i click on Button it sometimes shows the progressdialog and sometimes not show the progressdialog on click of button.
Asynchronous Task code is:
public class LoadData extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(MainActivity.this, "", "Loading...");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
LoadActivities(); // function to load data from url
}
});
return null;
}
#Override
protected void onPostExecute(Void unused)
{
pd.dismiss();
}
}
and on button click event call this as:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadMoreData().execute(null);
}
});
the wrong think you are doing is that in doInBackground you use runOnUiThreade . just remove that from your code . It solves your problem.
never use any thread in doInBackground.
Why you have taken run method again in doInBackground, doInBackground method performs computation on a background thread, so no need to take runOnUiThread
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
LoadActivities(); // function to load data from url
}
});
Just write
protected Boolean doInBackground(final String... args) {
try {
LoadActivities();
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
And also change new LoadMoreData().execute(); don't write null
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadMoreData().execute();
}});
Nirali's answer seems correct, just to make further explaination and some edits.
Progress Dialog will be shown by the time doInBackground method returns value. and in your code it just create another thread, and completes execution, so to display progress dialog by the time LoadActivities exectues, execute this statement in the same thread doInBackground executes, so change to following:
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
LoadActivities(); // function to load data from url
return null;
}
As I created a Progress bar using below code in a on click method of button. but after clicking button it takes 2-3 seconds to display progress bar.how to reduce that delay to start progress bar.
public void getProgressBar() {
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
progressBarStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = doSomeTasks();////I am loading service
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100 ) {
progressBar.dismiss();
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
}
}).start();
}
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myProgress = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
Use an AsyncTask instead. The example code in the link gives a good introduction on how to do it. In essence you do the job in doInBackground(), publish your progress using onProgressUpdate() and start your activiy in onPostExecute().
I'd like my application to show the indefinite progress bar (you know, the cycle) into the Activity's layout, just like the youtube Application. How could I do that? Thanks.
Hi you can use setProgressBarIndeterminateVisibility(boolean) to show indefinite progress bar.Here is the sample code:
private Button buttonUpStartUpload = null;
private boolean mToggleIndeterminate = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.lyt_upload_main);
setProgressBarIndeterminateVisibility(mToggleIndeterminate);
buttonUpStartUpload = (Button) findViewById(R.id.buttonUpStartUpload);
buttonUpStartUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
UploadingAsyncTask uploadingAsyncTask = new UploadingAsyncTask();
uploadingAsyncTask.execute("temp","doinback","returnparam");
}
});
}//onCreate Ends
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
public class UploadingAsyncTask extends AsyncTask<String, String, String>{
Uploader uploader = new Uploader();
ProgressDialog progDialogUpload = null;
int imageIndex = 1;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mToggleIndeterminate = !mToggleIndeterminate;
setProgressBarIndeterminateVisibility(mToggleIndeterminate);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
publishProgress("Finish","3");
return "success";
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if(values[0] == "Finish"){
imageIndex++;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equalsIgnoreCase("success") || result == "success"){
mToggleIndeterminate = !mToggleIndeterminate;
setProgressBarIndeterminateVisibility(mToggleIndeterminate);
}
}
}//UploadingAsyncTask ends