Android Example of using Thread Class for Multithreading App

Here is a simple example of using the Thread Class for a Multithreading application . Shows how to use the Progress Dialog, Handler, and running on the UI Thread. Also how to handle the Looper.prepare() error (“java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()”). If you are getting this error then you are trying to do work that should be done on the UI/Main thread. I have example in the code to handle this.

device-2014-04-09-130053

public class MainActivity extends Activity{

    	ProgressDialog pd;
    	volatile  Handler mapHandler = new Handler();

      /** You can use Thread anywhere but I will use it on onStart() **/
	    @Override
	    public void onStart() {
	      super.onStart();
		   pd = ProgressDialog.show(this, "Setting Up" , "");
		      Thread t = new Thread() {
		          public void run() {
                  /** All your work in done in here, 
                           I will be calling setup() for this example **/             
	                      setup();  
		          }
		        };
		        t.start();
	    }

         private void setup(){
           /** do stuff that doesn't relate to the UI including updating it **/
            blah blah blah

           /** Here is how to do the UI work and prevent the prepare.looper() error **/   
	    MainActivity.this.runOnUiThread(new Runnable() {
		  public void run() {   
		       pd.setMessage("Adding Map Markers"); //change the progress dialog
		       ((TextView) findViewById(R.id.information)).setText(R.string.select_pin);
			((Button)findViewById(R.id.share)).setVisibility(View.GONE);
			((Button)findViewById(R.id.direction)).setVisibility(View.GONE);
		   }
	     });// The UI thread is done

         /** Continue with your stuff **/
         blah blah blah

         /** Now you are done, you need to end the thread **/

	pd.dismiss(); // end the progress dialog
        /** You can use any Runnable, depending what you want your end result is **/
	mapHandler.post(Success); 
        }

	final Runnable Success = new Runnable() {
	      public void run() {
		  //maybe a popup or just do nothing	    	
	      }
	};

}

Graveyard Database Logo

Has everything you want to know about grave yards. Plus has many celebrites and world leaders graves. Pssst it is my other site

Google + Profile
Check out Android Photo Mapping, its a app/site I been working on
  • wholesale nfl jerseys
  • wholesale nfl jerseys china
  • wholesale sports jerseys