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
Related
I have tried to implement Async to handle the background unzipping of files with a progresbar however the unzip is happening while the progressbar displays 0%, after the unzipping the progresbar dismisses at 0%.. the onProgressUpdate method is not updating. my code below:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib = (ImageButton) findViewById(R.id.ImageButton01);
ib.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
new DownloadFileFromURL().execute(file_url);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
System.out.println("DIALOG:");
switch (id) {
case progress_bar_type: //
pDialog = new ProgressDialog(this);
pDialog.setMessage("Extracting. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
private void fileZ()
{
// TODO Auto-generated method stub
String zipFile = myDEST + myFolderImages + myFILEposterZIP;
String unzipLocation = myDEST + myFolderImages;
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
System.out.println("UNZIPPING");
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
fileZ();
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
Edit #1:
class ExtractFiles extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
// TODO Auto-generated method stub
Thread thread = new Thread()
{
public void run()
{
int prog = 0;
while(prog < 100)
{
pDialog.setProgress(prog);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
prog ++;
}
}
};
thread.start();
System.out.println("EXTRACTING...");
fileZ();
return null;
}
You don't update correctly your progress bar while you unzip the file..
Use a counter like :
count++;
and update progressbar..
publishProgress((int)((count));
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
I made a fragment and I am showing a progressDialog. When the orientation changes my progress dialog doesn't show again, while I am using a setRetainInstance(true).
Code is
public class FragmentTest extends Fragment implements OnClickListener
{
Button proceed;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(pDialog!=null)
{
pDialog.show();
}
}
class inner extends AsyncTask
{
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMessage("Processing...");
pDialog.setCancelable(false);
pDialog.setMax(900000000);
pDialog.show();
}
#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 onStop()
{
// TODO Auto-generated method stub
super.onStop();
if (pDialog!=null && pDialog.isShowing()){
pDialog.dismiss();
}
}
}
But my progress dialog is not showing. Can any one tell me how to solve the problem?
You need to create the instance of ProgressDialog before you show.
Best approach is to create a method showProgress
private void showProgress(){
pDialog = new ProgressDialog(getActivity());
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMessage("Processing...");
pDialog.setCancelable(false);
pDialog.setMax(900000000);
pDialog.show();
}
And call it when ever required to show the progress dialog.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
showProgress();
}
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();
}
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