How can I retain an instance of fragment in Android? - android

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();
}

Related

Progress Bar Remains At 0%

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));

Progress Dialog stops UI thread

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();
}
}
}

Confused about Simple Asyntask app

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

Fragment instance retain in android

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

Android - Loader for 1 record

Which is the best way to load the data for a single item (read only) detail activity?
Should i use LoaderManager or directly AsyncTask?
Use an Asyntask for best result:
Public class example extends AsyncTask<Void,Void,Void>
{
private ProgressDialog dialog;
public example(Context context){
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setTitle("Demo");
dialog.setMessage("Please Wait..");
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
}

Categories

Resources