23 April 2015

Progress Spinner in Dialog Fragment in Android

spinner logo
What we will do ?
->In this tutorial we will make a button which when pressed opens a dialogbox with spinner for sometime and then open another page.

What we need ?
  • An activity with a Button(activity_main.xml)
  • An activity with progress bar(activity_progressbar.xml)
  • An activity with result page(activity_finalpage.xml)
  • styles.xml
  • Java Classes to handle all three activities(MainActivity.java, DialogFrag.java, FinalPage.java)
  • Some additions in AndroidMainfest.xml
Step 1 : Create a new application by visiting File->New->Android Application Project.
make project

Step 2 : Give a Name to your Application (ProgressSpinnerdialog) and a package name(mia), then click on Next continuously then click Finish.

Step 3 : Make a button in activity_main.xml in a Linear Layout.
activity main
 Code for activity_main.xml is shown below.

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:paddingLeft="50dp"
      android:paddingRight="50dp"
      android:paddingTop="10dp" >
      <Button
         android:id="@+id/Button01"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="Click to launch" >
      </Button>
      </LinearLayout>
Step 4 : Make a new Android XML File in res->layout and name it as activity_progressbar.xml.
layout
activity_progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="horizontal" >
      <ProgressBar
         android:id="@+id/progress_bar_only"
         style="@style/ProgressBar.Spinner.Indeterminate.Small"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center"
         android:layout_weight="1"
         android:max="200"
         android:paddingBottom="1dp"
         android:paddingLeft="20dp"
         android:paddingRight="10dp"
         android:paddingTop="1dp" />
      <TextView
         android:id="@+id/waiting"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:ems="10"
         android:paddingBottom="1dp"
         android:paddingLeft="20dp"
         android:paddingTop="1dp"
         android:text="waitText"
         android:textSize="16sp" />
   </LinearLayout>

Step 5 : Make another Android XML File and name it as activity_finalpage.xml
final page
activity_finalpage.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/RelativeLayout1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >
      <TextView
         android:id="@+id/display_message"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:ems="10"
         android:paddingTop="10dp"
         android:text="Page Loaded"
         android:textSize="20sp" />
   </RelativeLayout>

Step 6 : Go to res->values->styles.xml and copy the code below in it.

styles.xml
<resources>
      <style name="AppBaseTheme" parent="android:Theme.Light">
      </style>
      <!-- Application theme. -->
      <style name="AppTheme" parent="AppBaseTheme">
         <!-- All customizations that are NOT specific to a particular API-level can go here. -->
      </style>
      <style name="ProgressBar.Spinner.Indeterminate.Small" parent="@android:style/Widget.Holo.Light.ProgressBar.Small">
         <item name="android:layout_width">wrap_content</item>
         <item name="android:layout_height">wrap_content</item>
         <item name="android:indeterminate">true</item>
      </style>
   </resources>

Step 7 : Go to src->com.mia.progressspinnerdialog ->.MainActivity.java

MainActivity.java
package com.mia.progressspinnerdialog;
  
   import android.app.Activity;
   import android.os.Bundle;
   import android.widget.Button;
   import android.widget.ProgressBar;
   import android.view.View;
   import android.view.View.OnClickListener;
  
   public class MainActivity extends Activity {
  
         int typeBar;                                
         ProgressBar progDialog;
         Button button1;
         DialogFrag fragment;
  
         @Override
         public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  button1 = (Button) findViewById(R.id.Button01);
                  button1.setOnClickListener(new OnClickListener(){
                           public void onClick(View v) {
                                 typeBar = 0;
                                 DialogFrag.context = getApplicationContext();
                                 fragment = DialogFrag.newInstance(typeBar); 
                                 fragment.show(getFragmentManager(), "Task 1");           
                           }
                  }); 
         } 
   }

Step 8 : Make a new class in src->com.mia.progressspinnerdialog and name it as DialogFrag. Copy the below code in it.

DialogFrag.java
package com.mia.progressspinnerdialog;
   
   import android.app.DialogFragment;
   import android.app.ProgressDialog;
   import android.os.Bundle;
   import android.os.Handler;
   import android.os.Message;
   import android.util.Log;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.ProgressBar;
   import android.content.Context;
   import android.content.Intent;
   
   public class DialogFrag extends DialogFragment {
   
         ProgressDialog progDialog;
         ProgressBar pbar;
         public static Context context;
         int barType;
         View v;
         private ProgressThread progThread;
         private static final int delay = 20;         
         private int maxBarValue;                     
         boolean threadStopped = false;
         boolean lightTheme = true;                   
     public DialogFrag() {        
     }
         static DialogFrag newInstance(int num) {
                  DialogFrag f = new DialogFrag();
                  Bundle args = new Bundle();
                  args.putInt("num", num);
                  f.setArguments(args);
                  return f;
         }
         public void onCreate(Bundle savedInstanceState){
                  super.onCreate(savedInstanceState);
                  barType = getArguments().getInt("num");
                  int style = DialogFragment.STYLE_NO_TITLE;
                  int theme = android.R.style.Theme_Holo_Dialog;
                  if(lightTheme){
                           theme = android.R.style.Theme_Holo_Light_Dialog;
                  }
                  this.setStyle(style, theme);  
         }
         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
                  if(barType == 0){
                           v = inflater.inflate(R.layout.activity_progressbar, container, false);
                           pbar = (ProgressBar) v.findViewById(R.id.progress_bar_only);
                  } 
                  maxBarValue = pbar.getMax();
                  progThread = new ProgressThread(handler);
                  progThread.start();
                  return v;
         }
         @Override
         public void onDestroy(){
                  super.onDestroy();
         }
         private void closeDialog(){
                  if(!threadStopped){
                           Intent i = new Intent(context, FinalPage.class);
                           startActivity(i);
                           if(!this.isDetached()) dismiss();
                  }
         }
         final Handler handler = new Handler() {
                  public void handleMessage(Message msg) {
                           int total = msg.getData().getInt("total");
                           pbar.setProgress(total);
                           if (total > maxBarValue){
                                 progThread.setState(ProgressThread.DONE);
                                 pbar.setVisibility(ProgressBar.INVISIBLE);
                                 v.setVisibility(View.INVISIBLE);
                                 closeDialog();
                                 threadStopped = true;
                           }
                  }
         };
         private class ProgressThread extends Thread {    
                  final static int DONE = 0;
                  final static int RUNNING = 1;
   
                  Handler mHandler;
                  int mState;
                  int total;
                  ProgressThread(Handler h) {
                           mHandler = h;
                  }
                  @Override
                  public void run() {
                           mState = RUNNING;   
                           total = 0;
                           threadStopped = false;
                           while (mState == RUNNING) {
                                 try {
                                          Thread.sleep(delay);
                                 } catch (InterruptedException e) {
                                          Log.e("ERROR", "Thread was Interrupted");
                                 }
                                 Message msg = mHandler.obtainMessage();
                                 Bundle b = new Bundle();
                                 b.putInt("total", total);
                                 msg.setData(b);
                                 mHandler.sendMessage(msg);   
                                 total++; 
                           }
                  }
                  public void setState(int state) {
                           mState = state;
                  }
         }
   }

 Step 9 : Make a new class in src->com.mia.progressspinnerdialog and name it as FinalPage. Copy the below code in it.

FinalPage.java
package com.mia.progressspinnerdialog;
  
   import android.os.Bundle;
   import android.support.v4.app.FragmentActivity;
  
   public class FinalPage extends FragmentActivity {
  
         @Override
         public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_finalpage); 
         }
   }

Step 10 : Make changes in AndroidManifest.xml as shown below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mia.progressspinnerdialog"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="16" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.mia.progressspinnerdialog.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
               android:name=".DialogFrag"
               android:label="DialogFragment" >
         </activity>
                  <activity
               android:name=".FinalPage"
               android:label="FinalPage" >
         </activity>
    </application>
</manifest>

Step 11 : Run the Project.
output mobile
output emulator

Explanation of the code :

Explanation from activity_main.xml :
  • We have a button with id Button01 in a Linear Layout.
Explanation from activity_progressbar.xml :
  •  We have a ProgressBar with a TextView in a Linear Layout.The style of progress bar is defined from styles.xml.
  • android:max defines the maximum value for the progress.
<ProgressBar
         android:id="@+id/progress_bar_only"
         style="@style/ProgressBar.Spinner.Indeterminate.Small"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center"
         android:layout_weight="1"
         android:max="200"
         android:paddingBottom="1dp"
         android:paddingLeft="20dp"
         android:paddingRight="10dp"
         android:paddingTop="1dp" />
Explanation from activity_finalpage.xml :
  •  We have a Text displayed on a simple Relative Layout.
Explanation from MainActivity.java :
  • We define an integer variable named typeBar, a ProgressBar variable progDialog, a Button and a Dialog Fragment.
int typeBar;
ProgressBar progDialog;
Button button1;
DialogFrag fragment;

  • We use onClick() method to perform action when button is pressed. We define typeBar to value 0 to denote a spinner.
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
 typeBar = 0;
  • getApplicationContext() method is used to hold the specific action of the Dialog Fragment.
DialogFrag.context = getApplicationContext();
  • Then we create a new instance of  Fragment using newInstance(). We use this instance to interact with the fragment (our dialogbox with spinner and text) using getFragmentManager() method. Task 1 is the tag for the fragment.
fragment = DialogFrag.newInstance(typeBar);  
fragment.show(getFragmentManager(), "Task 1");

Explanation from DialogFrag.java :
  • Create a new instance of class DialogFrag.
static DialogFrag newInstance(int num) {
DialogFrag f = new DialogFrag();
Bundle args = new Bundle();args.putInt("num", num);
f.setArguments(args);
return f;
}
  • Define theme for the dialog-box
int style = DialogFragment.STYLE_NO_TITLE;
int theme = android.R.style.Theme_Holo_Dialog;
if(lightTheme){
theme = android.R.style.Theme_Holo_Light_Dialog;
}
this.setStyle(style, theme);
  • Connect pbar variable to progressbar (progress_bar_only) from the layout.
pbar = (ProgressBar) v.findViewById(R.id.progress_bar_only);
  • Get the maximum value of progress and store it in maxBarValue. Then make thread progThread and start it using start().
maxBarValue = pbar.getMax();
progThread = new ProgressThread(handler);
progThread.start();
  • Code for opening FinaPage when dialog-box closes.
private void closeDialog(){
if(!threadStopped){
Intent i = new Intent(context, FinalPage.class);
startActivity(i);
if(!this.isDetached()) dismiss();
  • Handler displays the message in the dialog-box. getInt() gets integer value of text and compares it with maxBarValue. If it is higher the dialog-box will disappear.
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
pbar.setProgress(total);
if (total > maxBarValue){
progThread.setState(ProgressThread.DONE);
pbar.setVisibility(ProgressBar.INVISIBLE);
v.setVisibility(View.INVISIBLE);
closeDialog();
threadStopped = true;
  • All other code is simple java thread code.
Explanation from FinalPage.java
  • It opens the layout activity_finalpage when class object is called.
setContentView(R.layout.activity_finalpage);
Stay Tuned with Made In Android

Previous Page Next Page Home
Top