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
Related
I am showing some animation and making network request at the same time. Both are working fine independently. But when I try to place a progress dialog in asynctask the animation is not started until progress dialog until the onPostExecute(). My guess is that as the animation and progressdialog both run on the UI thread so only one can run at a time. Is there a way to show progress dialog and run animation at the same time both on the UI thread?
Here's my code:
public class DailyTarrotActivity extends FragmentActivity {
ImageView imageViewAnimation;
AnimationDrawable spinAnimation;
AnimatorSet set = new AnimatorSet();
FlipImageView imageViewCard;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_tarrot);
imageViewAnimation = (ImageView) findViewById(R.id.imageViewAnimation);
imageViewAnimation.setBackgroundResource(R.drawable.spin_animation);
imageViewCard = (FlipImageView) findViewById(R.id.imageViewCard);
spinAnimation = (AnimationDrawable) imageViewAnimation.getBackground();
new DailyTarrotAsyncTask().execute();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
Log.d("start", "focuschange");
if (hasFocus) {
spinAnimation.start();
}
}
public class DailyTarrotAsyncTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(DailyTarrotActivity.this);
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Thread thread = new Thread();
try {//just to mimic downloading behaviour
thread.sleep(10000);//animation starts only after 10 secs
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
Toast.makeText(DailyTarrotActivity.this, "async task finished",
Toast.LENGTH_SHORT).show();
}
}
}
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 main activiy i call a fragment and in fragment iam displaying a progress dialog in async task now my question is when orientation change my progress dialog restart and i want it retain its state iam using a retainInstance(true) but its not working.
my fragment code is
#Override
public void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(savedInstanceState!=null)
{
if(pDialog!=null)
{
pDialog.show();
}
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putString("status", "ok");
}
public void showProgress()
{
pDialog = new ProgressDialog(getActivity());
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMessage("Processing...");
pDialog.setCancelable(false);
pDialog.setMax(900000000);
pDialog.show();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment, container, false);
proceed=(Button) view.findViewById(R.id.b1);
proceed.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v)
{
new inner().execute();
}
class inner extends AsyncTask
{
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
showProgress();
}
#Override
protected Object doInBackground(Object... arg0)
{
int k=0;
for(int i=0;i<10000000;i++)
{
pDialog.incrementProgressBy(i);
for(int j=0;j<10000;j++)
{
k=k+j;
}
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Object result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("enter here");
pDialog.dismiss();
}
}
#Override
public void onPause()
{
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onStop()
{
// TODO Auto-generated method stub
super.onStop();
if (pDialog!=null && pDialog.isShowing()){
pDialog.dismiss();
}
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
You have to save your current progress in onDetach and use it again in onAttach. Example:
private ProgressDialog buildDialog() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
progressDialog.setTitle(getResources().getString(R.string.please_wait));
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(currentProgress);
progressDialog.setMax(100);
return progressDialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
attached = true;
if (taskStarted) {
progressDialog = this.buildDialog();
progressDialog.setMessage(getResources().getString(messageId));
progressDialog.show();
}
}
#Override
public void onDetach() {
super.onDetach();
if (progressDialog != null && progressDialog.isShowing()) {
currentProgress = progressDialog.getProgress();
progressDialog.dismiss();
progressDialog = null;
}
attached = false;
}
I wrote an example of this the other day. Here you go
https://gist.github.com/slightfoot/11368894
I have searched other posts but haven't found any describing my particular problem. Many of them refer to calling publishProgress from doInBackground. I am calling publishProgress from onPreExecute expecting a dialog to be displayed to inform a user that data is being fetched. The AsyncTask is being launched from the user making a selection from a Spinner. Rather than the dialog being displayed, the UI freezes until the AsyncTask completes. I have added in log messages and it appears that although publishProgress is called in onPreExecute, onProgressUpdate is not being executed until after doInBackground is completed.
The activity:
public class MainActivity extends Activity implements OnItemSelectedListener{
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
spinner = (Spinner)findViewById(R.id.spinner);
SpinnerAdapter adapter = new CustomSpinnerAdapter<String>(this, new String[]{"one", "two", "three"});
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi")
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
try{
FetchDataTask fetchDataTask = new FetchDataTask();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
fetchDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "data");
} else{
fetchDataTask.execute("data");
}
fetchDataTask.await();
} catch (InterruptedException e){
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public class FetchDataTask extends AsyncTask<String, Integer, Boolean> {
private final String TAG = FetchDataTask.class.getSimpleName();
private final Integer FETCHING_DATA = 1;
CountDownLatch countDownLatch = new CountDownLatch(1);
ProgressDialog dialog;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d(TAG,"Exiting onPostExecute");
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
publishProgress(FETCHING_DATA);
Log.d(TAG, "Exiting onPreExecute");
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog = ProgressDialog.show(MainActivity.this, "Fetching", "Data");
Log.d(TAG, "Exiting onProgressUpdate");
}
#Override
protected Boolean doInBackground(String... arg0) {
/*
* Fetching data here
*/
Log.d(TAG, "Exiting doInBackground");
countDownLatch.countDown();
return true;
}
public void await() throws InterruptedException{
countDownLatch.await();
}
}
}
The Spinner:
public class CustomSpinnerAdapter<T> implements SpinnerAdapter {
Context context;
T[] values;
public CustomSpinnerAdapter(Context context, T[] values){
this.context = context;
this.values = values;
for(T value: this.values){
Log.d("Spinner", value.toString());
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return values.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return values[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return android.R.layout.simple_spinner_dropdown_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView v = new TextView(context);
v.setTextColor(Color.BLACK);
v.setText(values[position].toString());
return v;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return this.getView(position, convertView, parent);
}
}
The view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
I am think this might have something to do with executing the AsyncTask from the Spinner selection because simply executing it in the Activity without connecting it to the Spinner does not have this problem. Any assistance would be appreciated.
You dont keep on showing dialog on progress update, instead you show it onPreExecute update it onProgressUpdate and hide it onPostExecute or cancel. and in your case you dont need the publish progress since progressBar is indefinite
#Override
protected void onPreExecute()
{
super.onPreExecute();
Log.d(TAG, "Exiting onPreExecute");
dialog = ProgressDialog.show(MainActivity.this, "Fetching", "Data");
}
#Override
protected Boolean doInBackground(String... arg0)
{
Log.d(TAG, "Exiting doInBackground");
countDownLatch.countDown();
//publishProgress(x);
return true;
}
public void await() throws InterruptedException
{
countDownLatch.await();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
Log.d(TAG, "Exiting onProgressUpdate");
// update progressbar value
// ex progresssBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
Log.d(TAG,"Exiting onPostExecute");
dialog.dismiss();
}
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.