[TinyTut] - Displaying a simple ProgressDialog

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Postby rcpinheiro » Fri Apr 02, 2010 7:16 pm

Hi!
I'm trying to use the code in this excellent post but Android keeps crashing. What I want:
1) Download a file at the start
2) A spinner is populated with the contents of the file downloaded

Here's the code:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public void onCreate(Bundle savedInstanceState) {
  3.  
  4.         super.onCreate(savedInstanceState);
  5.  
  6.  
  7.  
  8.         setContentView(R.layout.main);
  9.  
  10.         progressDialog = ProgressDialog.show(DownloadFile.this, "", "Loading, please wait...");
  11.  
  12.  
  13.  
  14.         new Thread() {
  15.  
  16.                 public void run() {
  17.  
  18.                         try{
  19.  
  20.                                 reader=readURL("http://domain.net/spinner.txt"); // Download the file
  21.  
  22.                         } catch (Exception e) { }
  23.  
  24.                                                
  25.  
  26.                         // dismiss the progress dialog
  27.  
  28.                         progressDialog.dismiss();
  29.  
  30.  
  31.  
  32.                // Change the spinner values with the downloaded values
  33.  
  34.                spinner1 = (Spinner) findViewById(R.id.Spinner01);
  35.  
  36.                spinner1.setPrompt("Values:");
  37.  
  38.  
  39.  
  40.                ArrayAdapter adapter=new ArrayAdapter(DownloadFile.this,android.R.layout.simple_spinner_dropdown_item);
  41.  
  42.  
  43.  
  44.                         // populate spinner
  45.  
  46.                         try {
  47.  
  48.                                  while ((line = reader.readLine()) != null)  adapter.add(line);
  49.  
  50.                          } catch (IOException e) { }
  51.  
  52.  
  53.  
  54.                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);                  
  55.  
  56.                spinner1.setAdapter(adapter);    
  57.  
  58.             }
  59.  
  60.         }.start();
  61.  
  62.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


The application crashes after trying to change the spinner content. Is it not possible to change UI inside a Thread()?
Thanks in advance!
rcpinheiro
Junior Developer
Junior Developer
 
Posts: 13
Joined: Fri Apr 02, 2010 6:45 pm

Top

Postby rcpinheiro » Fri Apr 02, 2010 11:18 pm

Found the solution! I had to create a Handler to pass messages between the download routine and the UI.
rcpinheiro
Junior Developer
Junior Developer
 
Posts: 13
Joined: Fri Apr 02, 2010 6:45 pm

Progress bar and thread lost on screen rotation

Postby Martin Eigo » Fri May 14, 2010 3:59 pm

I was using code in this thread and trying to add a progress bar dialog to my app but I found the reference to it disappeared when I rotated the screen because the activity was destroyed and created again. I didn't have much luck looking on-line but I eventually figured out a solution and wrote an article on how I did it.

Tells you how to manage a thread and show the percentage complete in the progress dialog's progress bar and keep the thread and progress dialog going even though screen rotations destroy the activity.

Unfortunately this forum's rules do not allow me to post url's until I've had my account long enough so I'll try to post the URL tomorrow.
Ride on and rock out
Martin Eigo
Freshman
Freshman
 
Posts: 2
Joined: Fri May 14, 2010 3:35 pm
Location: London

Re: Progress bar and thread lost on screen rotation

Postby Martin Eigo » Tue May 18, 2010 12:25 pm

Here is the URL for dealing with orientation changes and keeping the progress dialog updating.

http://www.eigo.co.uk/Threads-and-Progress-Dialogs-in-Android-Screen-Orientation-Rotations.aspx

Hope this helps someone else
Ride on and rock out
Martin Eigo
Freshman
Freshman
 
Posts: 2
Joined: Fri May 14, 2010 3:35 pm
Location: London

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby cdavaz » Thu May 20, 2010 1:24 am

I have tried this example:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 @Override
  2.                 public void onCreate (final SQLiteDatabase db) {
  3.                         progress = ProgressDialog.show(
  4.                                 context,
  5.                                 context.getResources().getString(R.string.first_time),
  6.                                 context.getResources().getString(R.string.installing_database),
  7.                                 true
  8.                         );
  9.                        
  10.                         new Thread() {
  11.                                 public void run () {
  12.                                         try {
  13.                                                 loadSql(PATH_TABLE, db);
  14.                                                 db.beginTransaction();
  15.                                                 try {
  16.                                                         loadSql(PATH_DATA, db);
  17.                                                         db.setTransactionSuccessful();
  18.                                                 } finally {
  19.                                                         db.endTransaction();
  20.                                                 }
  21.                                         } catch (Exception e) { }
  22.                                        
  23.                                         progress.dismiss();
  24.                                 }
  25.                         }.start();
  26.                 }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


This brings the progress dialog up however since the work is being run in a thread, onCreate returns right away and my original activity which requires the work being done in the thread to be completed first crashes (it can't find the database tables that the thread is loading). If I simply don't do the work in the thread like this code shows below, the progress dialog never shows. Any ideas?

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 public void onCreate (final SQLiteDatabase db) {
  2.                         progress = ProgressDialog.show(
  3.                                 context,
  4.                                 context.getResources().getString(R.string.first_time),
  5.                                 context.getResources().getString(R.string.installing_database),
  6.                                 true
  7.                         );
  8.  
  9.                         loadSql(PATH_TABLE, db);
  10.                         db.beginTransaction();
  11.                         try {
  12.                                 loadSql(PATH_DATA, db);
  13.                                 db.setTransactionSuccessful();
  14.                         } finally {
  15.                                 db.endTransaction();
  16.                         }
  17.                
  18.                   progress.dismiss();
  19.                 }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
cdavaz
Freshman
Freshman
 
Posts: 7
Joined: Wed May 05, 2010 12:21 am

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby padde » Thu May 20, 2010 4:21 am

I would use a AsyncTask that runs the DB init stuff and handles the ProgressDialog.
If the user hit the back button while DB init is running the app simply close itself.
You could of course add some r-u-sure dialog thing before close.
If the DB init is finished you call a method where the app goes on.. whatever it is in your case.

Here is an example of what i mean:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import android.app.Activity;
  2. import android.app.ProgressDialog;
  3. import android.content.DialogInterface;
  4. import android.os.AsyncTask;
  5. import android.os.Bundle;
  6. import android.widget.TextView;
  7.  
  8. public class Test extends Activity {
  9.     public void onCreate(Bundle savedInstanceState) {
  10.         super.onCreate(savedInstanceState);
  11.         setContentView(R.layout.main);
  12.  
  13.         new DoInBackground().execute();
  14.     }
  15.    
  16.    
  17.     private void goOn() {
  18.         ((TextView) findViewById(R.id.text)).setText("Post DB init");
  19.     }
  20.    
  21.     private class DoInBackground extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener
  22.     {
  23.         private ProgressDialog dialog;
  24.        
  25.         protected Void doInBackground(Void...pParams) {
  26.             // do your DB stuff here
  27.             try {
  28.                 Thread.sleep(3000);  //just sleep 3sec to simulate
  29.             } catch (InterruptedException e) {}
  30.             return null;
  31.         }
  32.        
  33.         protected void onPostExecute(Void pVoid) {
  34.             dialog.dismiss();
  35.             // call a method that runs your code after the DB init
  36.             goOn();
  37.         }
  38.  
  39.         protected void onPreExecute() {
  40.             dialog = ProgressDialog.show(Test.this, "", "Please wait...", true, true, this);
  41.         }        
  42.  
  43.         protected void onCancelled() { finish(); }
  44.         public void onCancel(DialogInterface dialog) { cancel(true); }
  45.     }    
  46. }
  47.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


Hope this helps.
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Top

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby cdavaz » Thu May 20, 2010 6:32 pm

padde wrote:I would use a AsyncTask that runs the DB init stuff and handles the ProgressDialog.
If the user hit the back button while DB init is running the app simply close itself.
You could of course add some r-u-sure dialog thing before close.
If the DB init is finished you call a method where the app goes on.. whatever it is in your case.

Here is an example of what i mean:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import android.app.Activity;
  2. import android.app.ProgressDialog;
  3. import android.content.DialogInterface;
  4. import android.os.AsyncTask;
  5. import android.os.Bundle;
  6. import android.widget.TextView;
  7.  
  8. public class Test extends Activity {
  9.     public void onCreate(Bundle savedInstanceState) {
  10.         super.onCreate(savedInstanceState);
  11.         setContentView(R.layout.main);
  12.  
  13.         new DoInBackground().execute();
  14.     }
  15.    
  16.    
  17.     private void goOn() {
  18.         ((TextView) findViewById(R.id.text)).setText("Post DB init");
  19.     }
  20.    
  21.     private class DoInBackground extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener
  22.     {
  23.         private ProgressDialog dialog;
  24.        
  25.         protected Void doInBackground(Void...pParams) {
  26.             // do your DB stuff here
  27.             try {
  28.                 Thread.sleep(3000);  //just sleep 3sec to simulate
  29.             } catch (InterruptedException e) {}
  30.             return null;
  31.         }
  32.        
  33.         protected void onPostExecute(Void pVoid) {
  34.             dialog.dismiss();
  35.             // call a method that runs your code after the DB init
  36.             goOn();
  37.         }
  38.  
  39.         protected void onPreExecute() {
  40.             dialog = ProgressDialog.show(Test.this, "", "Please wait...", true, true, this);
  41.         }        
  42.  
  43.         protected void onCancelled() { finish(); }
  44.         public void onCancel(DialogInterface dialog) { cancel(true); }
  45.     }    
  46. }
  47.  
Parsed in 0.042 seconds, using GeSHi 1.0.8.4


Hope this helps.


This is excellent, thanks! I'm going to give it a shot.

UPDATE: This is working beautifully now. Had to add a flag though thats gets set by testing if the database needs to be created or upgraded. If so then the flag is set to true and the activity's onResume will not render the page as it normally would (and instead the goOn() function you show above will). If the flag is not set then none of this code runs at all and onResume renders the display as usual.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. // In my DbAdapter class:
  2.         public boolean willCreateOrUpgradeDatabase () {
  3.                 File dbFile = new File(DATABASE_DIR + DATABASE_NAME);
  4.                 if (dbFile.exists()) {
  5.                         SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
  6.                         int thisVersion = db.getVersion();
  7.                         db.close();
  8.                         return thisVersion < DATABASE_VERSION;
  9.                 } else {
  10.                         return true;
  11.                 }
  12.         }
  13.  
  14. // In my ListActivity subclass:
  15.         @Override
  16.         public void onCreate(Bundle savedInstanceState) {
  17.                 super.onCreate(savedInstanceState);
  18.                
  19.                 dbHelper = new RTSHDbAdapter(this);
  20.                
  21.                 if (dbHelper.willCreateOrUpgradeDatabase()) {
  22.                         // Launch ASyncTask
  23.                         firstTime = true;
  24.                         new SetupDatabase().execute();
  25.                 } else {
  26.                         dbHelper.open();
  27.                 }
  28.         }
  29.        
  30.         abstract void display ();
  31.        
  32.         protected void continueAfterSetupDatabase () {
  33.                 display();
  34.         }
  35.  
  36.         @Override
  37.         public void onResume () {
  38.                 super.onResume();
  39.                 if (!firstTime) display();             
  40.         }
  41.  
  42.         private class SetupDatabase extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener {
  43.                 private ProgressDialog dialog;
  44.  
  45.                 protected Void doInBackground (Void... parmas) {
  46.                         // do your DB stuff here
  47.                         try {
  48.                                 Log.v(TAG, "SetupDatabase#doInBackground() called");
  49.                                 dbHelper.open();
  50.                         } catch (Exception e) {
  51.                                 e.printStackTrace();
  52.                         }
  53.                         return null;
  54.                 }
  55.  
  56.                 protected void onPostExecute (Void pVoid) {
  57.                         dialog.dismiss();
  58.                         continueAfterSetupDatabase();
  59.                         firstTime = false;
  60.                 }
  61.  
  62.                 protected void onPreExecute () {
  63.                         dialog = ProgressDialog.show(
  64.                                 RTSHListActivity.this,
  65.                                 "",
  66.                                 getResources().getString(R.string.installing_database),
  67.                                 true,
  68.                                 true,
  69.                                 this
  70.                         );
  71.                 }
  72.  
  73.                 protected void onCancelled () {
  74.                         finish();
  75.                 }
  76.  
  77.                 public void onCancel (DialogInterface dialog) {
  78.                         cancel(true);
  79.                 }
  80.         }
  81.  
Parsed in 0.044 seconds, using GeSHi 1.0.8.4
cdavaz
Freshman
Freshman
 
Posts: 7
Joined: Wed May 05, 2010 12:21 am

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby soubhab » Tue Jun 22, 2010 6:31 am

Fantastic.........but when I was changing emulator from portrait to horizontal or horizontal to portrait then the application crashed.........here is the code and the layout xml...
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.example.progressdialog;
  2.  
  3. import android.app.Activity;
  4. import android.app.ProgressDialog;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;
  9.  
  10. public class Progress extends Activity implements OnClickListener {
  11.        
  12.         ProgressDialog myProgressDialog = null;
  13.        
  14.     @Override
  15.     public void onCreate(Bundle icicle){
  16.         super.onCreate(icicle);
  17.  
  18.         /* Create a very simple button */
  19.        
  20.         setContentView(R.layout.main);
  21.         Button b = (Button) findViewById(R.id.Button);
  22.        
  23.         /* Assign the OnClicklistener to it,
  24.          * that will fake some work and
  25.          * display a progress-bar */
  26.         b.setOnClickListener(this);
  27.     }
  28.         public void onClick(View arg0) {
  29.                 // TODO Auto-generated method stub
  30.                  myProgressDialog = ProgressDialog.show(Progress.this,
  31.                  "Please wait...", "Doing Extreme Calculations...", true);
  32.                  new Thread() {
  33.          public void run() {
  34.                  try{
  35.                          // Do some Fake-Work
  36.                          sleep(3000);
  37.                  } catch (Exception e) { }
  38.                  // Dismiss the Dialog
  39.                  myProgressDialog.dismiss();
  40.                 }
  41.                  }.start();    
  42.         }      
  43. }
  44.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4

there is the layout.......
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    android:orientation="vertical"
  4.    android:layout_width="fill_parent"
  5.    android:layout_height="fill_parent"
  6.    >
  7. <TextView  
  8.    android:layout_width="fill_parent"
  9.    android:layout_height="wrap_content"
  10.    android:text="@string/hello"
  11.    />
  12. <Button
  13.         android:id = "@+id/Button"
  14.         android:layout_width="wrap_content"
  15.    android:layout_height="wrap_content"
  16.    android:text = "Show ProgressBar" />
  17. </LinearLayout>
  18.  
Parsed in 0.003 seconds, using GeSHi 1.0.8.4
soubhab
Once Poster
Once Poster
 
Posts: 1
Joined: Sat May 29, 2010 6:21 pm

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby halwaraj » Sat Jun 26, 2010 7:01 pm

Hey man,

Great tutorial.

I am just starting off. So was going through some tutorials. Lets see where do I get to.

Halwa
http://drapl.com/
halwaraj
Once Poster
Once Poster
 
Posts: 1
Joined: Sat Jun 26, 2010 6:58 pm

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby phonepony » Tue Jul 06, 2010 7:18 am

Did you check the code while doing orientation changes? If you don't use the activity mechanism for managing dialogs, or explicitly manage it yourself, you might get suck with inner class runnable pointing to a destroyed activity, and doing visibility requests on it.
phonepony
Freshman
Freshman
 
Posts: 3
Joined: Fri Jul 02, 2010 9:34 am

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby noiz77 » Sat Jul 24, 2010 1:05 am

So I have the code that loads the dialog box but then FCs the app. It is trying to download an image from the web and display it. From what I have read it looks like I need to use a handler to make changes to the UI, but it still seems unclear to me. If someone could help me out, here is the function that I am using that is FCing.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. void downloadFile(String fileUrl){
  2.    loadingDialog = ProgressDialog.show(testing.this,   
  3.                 "Please wait...", "Loading...", true);
  4.         new Thread() {
  5.                                 public void run() {
  6.           try {
  7.                    Bitmap bmImg;
  8.                    URL myFileUrl = new URL(webcamURLs[camNumber]);//fileUrl);
  9.                    theCam.setText(webcamURLs[camNumber]);
  10.                HttpURLConnection conn = (HttpURLConnection)myFileUrl.openConnection();
  11.                conn.setDoInput(true);
  12.                conn.connect();
  13.                theCam.setText("Connected");
  14.                int length = conn.getContentLength();
  15.                InputStream is = conn.getInputStream();
  16.                theCam.setText("Got stream");
  17.                bmImg = BitmapFactory.decodeStream(is);
  18.                imView.setImageBitmap(bmImg);
  19.           } catch (IOException e) {
  20.                // TODO Auto-generated catch block
  21.                   theCam.setText("Error!!!");
  22.                e.printStackTrace();
  23.           }
  24.           loadingDialog.dismiss();
  25.         }
  26.                         }.start();
  27.          
  28.      }
Parsed in 0.040 seconds, using GeSHi 1.0.8.4

Can someone help me with implementing what I need to in this function to have to work correctly. webcamURLs is a string array that I put in the class that has all of the URLs for the images I am trying to get and camNumber is an int that I have pointed to the correct image.
noiz77
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Jun 30, 2010 4:32 pm

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby limteckchai » Mon Jul 26, 2010 3:30 am

Hi,

On the line
new DoInBackground().execute();
i get an error, unable to make reference ....
Anyone shares the same problem???

What i m trying to do is to retrive data from web, and place it in a listview.
That java file extended ListActivity (If that makes a difference)

I also hear from you guys that one way of updating the view is using Handlers, is there an example i can follow??
limteckchai
Experienced Developer
Experienced Developer
 
Posts: 92
Joined: Mon Jun 28, 2010 3:33 am

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby wingi » Thu Sep 09, 2010 6:32 am

I found a complete code example for the progress br example using the NotificationManager.

See it on http://united-coders.com/nico-heid/show ... om-android .
wingi
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Sep 09, 2010 6:30 am

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby Vtune » Thu Dec 16, 2010 3:27 pm

Great and handy thread here, but still have a question about the turning circle. Can it be replaced by another image/drawable? If yes, somebody knows how and wants to share it? :roll:
--http://www.timvk.be-- http://goo.gl/4qmQ9
SE Xperia X10 White - HTC Magic 32A - SE G900i - SE K750i
Vtune
Freshman
Freshman
 
Posts: 3
Joined: Tue Nov 09, 2010 4:06 pm
Location: Lokeren - Belgium

Re: [TinyTut] - Displaying a simple ProgressDialog

Postby sheikh.aman » Mon Jan 03, 2011 8:46 am

although the posts look quite old, but I feel that the dialog has a custom layout.
how to do that if it really has a custom layout!?
Impossible is Nothing
User avatar
sheikh.aman
Developer
Developer
 
Posts: 40
Joined: Sat Mar 20, 2010 7:52 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 8 guests