JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Switch in Android 4.0

May 24, 2013 by Krishna Srinivasan Leave a Comment

A Switch is a widget introduced in Android 4.0, which is a two state toggle button. You can drag it to one side or the other with your fingers to toggle an option between two states, or you can simply tap on it to change that state of an option(ON or OFF). A Switch is a variant of the CheckBox. A Switch with ON and OFF state is as below,

The methods which are available for switch are as below,

setChecked() : Used to change the state of the Switch to On or OFF.
setTextOn() : Used to set the text that is to be displayed when the Switch is ON.
setTextOff() : Used to set the text that is to be displayed when the Switch is in OFF state.
getTextOn() : Used to get the text which is associated with the Switch in ON state.
getTextOff() : Used to get the text which is associated with the Switch in OFF state.

Note: since “switch” is a reserved word in JAVA, the widget is called as “Switch” and not as”switch”.

Creating a Switch

The below snippet tells you how to add a Switch widget into a layout file,

[java]<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON" />[/java]

You can register a listener ie. an instance of OnCheckedchangeListener() which handles the state change event of the Switch. The callback that is to be implemented is OnCheckedChange() that receives the Switch whose state is changed and the new state of the Switch.

Let us now create a sample project that explains you how to deal with Android Switch widget.

Step 1: Setting up android working Environment

Since Switch is introduced in android 4.0, I would be using Android 4.0 platform for developing this example. For more information on how to set up the working environment, please go through the post, Environment.

Step 2: Create an android project

Create an android project named “Switchdemo” with the launcher activity “SwitchdemoActivity”. If you are not familiar with creating android project, please go through the post Create an Android project.

Step 3: Create the required layouts

I would be using main.xml (the automatically created layout) for this example. If you want to know more about android layouts, please refer to one of our articles on Layouts. The code of the main.xml layout file is as below,

[java]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<Switch
android:id="@+id/switch1"
android:text="Switch 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dip" />

<Switch
android:text="Switch 2(Default on)"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="32dip"
android:checked="true" />

<Switch
android:text="Switch 3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dip"
android:textOff="LEFT"
android:textOn="RIGHT" />
</LinearLayout>

</LinearLayout>
[/java]

As you see in the above code,

  • Switch 1: This is the standard switch whose android:text attribute is set to “Switch 1”. It is just a simple switch which displays the text “Switch 1” and a button. The button’s default state is “OFF”. You can always change the default state which is being done for the second switch.
  • Switch 2: This is the switch whose default state is set to “ON” state by using android:checked property. This switch displays the text “Switch 2”. This switch has android:layout_width property set to the value “match_parent” because of which you can see the switch’s button being aligned to the right side of the parent.
  • Switch 3: This is the switch whose button displays the associated text “LEFT” when the switch is in “OFF” state and “RIGHT” when the switch is in “ON” state. This is being done using the properties android:textOff and android:textOn.

Step 4: Create the required Activities

I would be using the launcher activity SwitchdemoActivity which is being created when you create your project. The code remains unaltered. We would be altering SwitchdemoActivity.java as we move on with this tutorial. The code of your launcher activity SwitchdemoActivity.java is as below,

[java]package my.app;

import android.app.Activity;
import android.os.Bundle;

public class SwitchdemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}[/java]

Step 5: Declare your activities in AndroidManifest.xml file

Your launcher activity is declared automatically when your create your android application. If you want to know more about Manifest file, please go through the post manifest.
Your AndroidManifest.xml has the below code,

[java]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".SwitchdemoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>[/java]

Step 6: Run your application

Select the app->right click->Run As-> Android application.
The activity “SwitchdemoActivity” fires up as below,

As you can observe, the “Switch 1” has a button with OFF state(default), “Switch 2” with default being set to “ON” state and “Switch 3” with the associated text for the states being changed to “LEFT” and “RIGHT”.

Now change the states of all switches by simply tapping on it. The three switches with state being changed is as below,

So far you have seen how to create a simple switch in android and how to change the state and text associated with it. Now let us see how to add listeners which handles the state change event of the switch. As i said earlier, we have to register OnCheckedchangeListener() for android switches.

Change the “SwitchdemoActivity.java” code to the below code,

[java]package my.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.Toast;

public class SwitchdemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Switch s = (Switch) findViewById(R.id.switch1);
if (s != null) {
s.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
String state="OFF";
if(isChecked){
state="ON";
}
Toast.makeText(getApplicationContext(), "Switch 1 is "+state,Toast.LENGTH_LONG).show();
}
});
}
}

}[/java]

In the above code I have implemented the logic for displaying the state of the Switch 1. Since onCheckedChanged() callback gives the state of each switch whose state has been changed through the parameter “isChecked”, we can make use of this to display the new state of the Switch. The logic is pretty simple. After getting the new state of the Switch, I am displaying it using the “Toast” message. If you are not familiar with using Toast messages, please go through the post Toast.

The Toast message displayed when “Switch 1” is pressed is as below,

The above picture is when the state of the Switch is changed from OFF to ON state. And when the Switch is changed from ON to OFF state, the Toast is displayed as below,

Creating Standalone Switch

You can create a Switch without the associated text which is just like a simple “Toggle Button”. For that you should not provide the property “android:text” in the respective Switch tag. Follow the below code to create such a Switch,

[java]<Switch
android:id="@+id/switch4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
[/java]

The Standalone Switch is as below,

This is how you can create Switches in Android. Hope this tutorial helped you. Please post your comments for furthur queries.

Filed Under: Google Android Tagged With: Android

How to create Dialog activity in Android?

May 23, 2013 by Krishna Srinivasan Leave a Comment

A dialog is a small window which prompts the user to enter additional information. We have discussed about how to create a dialog in one of our articles Dialog.  In this tutorial we would be learning how to create an activity dialog in android. As shown in the below figure, an Activity Dialog is like an Activity floating over another Activity(parent activity).

Dialog activity in Android Example - 1

You can’t access the parent activity until the dialog activity is destroyed. When the dialog activity closes, the parent activity gets its focus.

To create a floating activity, you need to apply dialog Theme while defining the activity entry in the AndroidManifest.xml file. Follow the below code to know about how to add the Theme to the Manifest file,

[java]<activity
android:label="@string/app_name"
android:name=".DialogActivityDemoActivity"
android:theme="@android:style/Theme.Dialog" >
……….
</activity>[/java]

If you use ‘Theme.Dialog’ for your activity, it would be shown as a floating Dialog. You can create buttons like “OK”, “CANCEL” etc for this dialog through the activity’s layout.

Step 1: Set up Android working environment

We have already discussed about how to set up android working environment in one of our articles, please go through the post Environment. if you are not familiar with the android environment.

Step 2: Create an Android application

To know how to develop a simple android application, please refer to the post Create a simple app.

Step 3: Create the required layouts

Here I would be using main.xml. I would just add a simple button to this layout to launch our floating Activity. The code of the main.xml is as below,

[java]<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#d8dff2"
android:orientation="vertical" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="183dp"
android:background="#3790e8"
android:text="Start a floating Activity" />

</RelativeLayout>[/java]

The layout xml for the dialog activity is “floatingactivity.xml”. This layout file just has a textview that displays a text when the activity is started. The code of the floatingactivity.xml is as below,

[java]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="150dip"
android:layout_height="100dip"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dip"
android:layout_marginTop="40dip"
android:text="I am a floating Activity" />

</LinearLayout>[/java]

Step 3: Create the required activities

Here I would be using the launcher activity DialogActivityDemoActivity which is created automatically when you create your sample application, as a parent activity to launch our floating activity (DialogActivity.java). Our floating Activity is launched when a button named “Start a floating activity” in the parent activity is clicked. The code of the parent activity  DialogActivityDemoActivity.java is as below,

[java]package my.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DialogParentActivity extends Activity {
Button btnsecond_activity;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnsecond_activity=(Button)findViewById(R.id.button1);
btnsecond_activity.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(getApplicationContext(), DialogActivity.class);
startActivity(intent);
}
});
}
}[/java]

As you can see in the above code, we are launching a new dialog activity on click of a button in the parent activity. The DialogActivity.java has the below code,

[java]package my.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class DialogActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.floatingactivity);
}

}
[/java]

I have made the dialog activity with no Title.

Step 4: Define the activities in AndroidManifest.xml

Your launcher activity is declared automatically by the android system. To know more about AndroidManifest.xml, please refer the post Manifest. The content of your manifest file is as below,

[java]<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.app"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".DialogParentActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="DialogActivity"
android:theme="@android:style/Theme.Dialog" >
</activity>
</application>

</manifest>[/java]

You can notice the Theme.Dialog is being applied to the activity “DialogActivity”.

Step 5: Run your application

The parent Activity fires up as below,

Dialog activity in Android Example - 2 - parentdialog

Click on the button “Start a floating Activity”. The dialog activity opens up as below,

Dialog activity in Android Example - 3

Even though this is an Activity for all the purposes, it can behave as a dialog inside your UI, partially covering the parent activity. Click the window outside the Floating Dialog, the dialog would be closed and the parent activity gets focus. If you want to dismiss the dialog activity on click of a button, then you need to add a button to the dialog activities layout and you can add listeners for its click events. If you don’t want the dialog activity to be closed when you click the surface outside the dialog, add the below line to your dialog activities code,

[java]this.setFinishOnTouchOutside(false);[/java]

If you add the above line , you can handle the click events of the dismiss buttons in case if you add them to your layouts.

This is how you can create an Activity as a dialog in Android. “Theme.Dialog” can be used to create the look and feel of the dialogs, with all the features of a full-blown Activity. Hope this helped you. If you have any queries, please post it in comments section.

Filed Under: Google Android Tagged With: Android

How to create CheckBoxes in Android

May 22, 2013 by Krishna Srinivasan Leave a Comment

CheckBox is a fully implemented widget provided by Android. Checkboxes are used for selecting one or more options from a set. In this tutorial we would be discussing about creating the standard and customized CheckBoxes. CheckBox is a special type of button that has two states, checked and unchecked.
The CheckBox in Android is as below.

As you can see the above picture, CheckBox in android has a TextView whose properties can be used to format the widget. One must avoid using a single checkbox to turn an option off or on. The checked event of the CheckBox is handled by setting the onCheckedChangeListener for the CheckBox. The callback for the listener is onCheckedChanged(), which is responsible for receiving the CheckBox whose state has changed and its new state.

Creating a CheckBox

You can create a CheckBox by creating an instance of android.widget. CheckBox as below,

[java]&amp;amp;lt;CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Check Me" /&amp;amp;gt;[/java]

Within Java, you can manage the state of a checkbox by using the following,

  •  isChecked() : used to obtain the state of the CheckBox.
  • toggle() : toggles the CheckBox state.
  • setChecked() : Used to set the CheckBox state to checked or unchecked.

Let us now create a sample application that shows the usage of CheckBoxes in Android.

Step 1: Set up the android development environment

This topic has already been discussed in one of our previous posts Environment. Please refer the post for more queries. I would be using Android 4.0 for this example

Step 2: Create An Android Project

Create an Android project named “CheckBoxDemo” with the launcher activity CheckBoxDemoActivity.java. For more information on how to create a new project in android, please refer to the post Create an android project.

Step 3: Create the required layouts

I would be using main.xml layout file. To know more about layout xml files, please go through the post Layouts. Open the main.xml file and paste the below code.

[java]&amp;amp;lt;?xml version="1.0" encoding="utf-8"?&amp;amp;gt;
&amp;amp;lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" &amp;amp;gt;

&amp;amp;lt;TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dip"
android:text="CheckBox Demo"
android:textSize="18sp"
android:textStyle="bold" /&amp;amp;gt;

&amp;amp;lt;CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="CheckBox: Unchecked" /&amp;amp;gt;

&amp;amp;lt;/RelativeLayout&amp;amp;gt;[/java]

As you can see in the above code, the main.xml has a RelativeLayout which in turn has a textview and a checkbox. The CheckBox tag is used to create the Checkbox widget.

Step 4: Create the required activities

The launcher Activity CheckBoxDemoActivity.java. has the below code,

[java]package my.app;

import android.app.Activity;
 import android.os.Bundle;
 import android.widget.CheckBox;
 import android.widget.CompoundButton;
 import android.widget.CompoundButton.OnCheckedChangeListener;

public class CheckBoxDemoActivity extends Activity implements OnCheckedChangeListener {
 CheckBox ck1;

/** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

ck1=(CheckBox)findViewById(R.id.checkBox1);
 ck1.setOnCheckedChangeListener(this);

}

//Called when the checked state of a compound button has changed
 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub

if(isChecked){
 ck1.setText("CheckBox: Checked");
 }
 else{
 ck1.setText("CheckBox: Unchecked");
 }

}
 }[/java]

Each CheckBox is managed separately. As you can see, we have registered a listener which is to be notified when the state of the Chekcbox changes. In this example, we would be changing the text of the checkbox when the user clicks on it.
As you can notice, we have registered onCheckedChangeListener and not onClickedListener as in the case of normal button. The callback for the listener is onCheckedChanged(). This callback receives the CheckBox whose state has changed.

Step 5: Declaring the Activities in AndroidManifest.xml

The AndroidManifest.xml file has the below code. To know more about manifest file, please refer the post Manifest.

[java]
&amp;amp;lt;?xml version="1.0" encoding="utf-8"?&amp;amp;gt;
&amp;amp;lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.app"
android:versionCode="1"
android:versionName="1.0" &amp;amp;gt;

&amp;amp;lt;uses-sdk android:minSdkVersion="14" /&amp;amp;gt;

&amp;amp;lt;application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" &amp;amp;gt;
&amp;amp;lt;activity
android:label="@string/app_name"
android:name=".CheckBoxDemoActivity" &amp;amp;gt;
&amp;amp;lt;intent-filter &amp;amp;gt;
&amp;amp;lt;action android:name="android.intent.action.MAIN" /&amp;amp;gt;

&amp;amp;lt;category android:name="android.intent.category.LAUNCHER" /&amp;amp;gt;
&amp;amp;lt;/intent-filter&amp;amp;gt;
&amp;amp;lt;/activity&amp;amp;gt;
&amp;amp;lt;/application&amp;amp;gt;

&amp;amp;lt;/manifest&amp;amp;gt;[/java]

Step 6: Run your application

Select your project->Right click->Run As->Android Application
Your launcher activity opens up as below,

At first the CheckBox is in unchecked state as shown by the TextView. Clicking the CheckBox immediately updates its text as below,

You can see the changed text in the above figure. Unchecked has been changed to checked when the CheckBox state is checked.

Creating custom CheckBox

Till now we have studied how to create a standard CheckBox in Android. So now you would be learning how to create custom CheckBox in android. Like all widgets, the standard CheckBox can be customized. You can change the color, shape and behaviors. This is done by creating a XML selector and assigning that selector to the CheckBox in your layout. selectors are the elements provided by android which allows users to create a single reference to multiple images and the conditions under which they shuold be visible. Follow below steps for creating custom CheckBoxes.

  • Prepare two images for CheckBox state. Here in this tutorial I would be using a Red square for CheckBox unchecked state and Green square for a checked state. Place these images in res/drawable folder. checked.png is to display when the CheckBox is in checked state. unchecked.png is to display when the CheckBox is in unchecked state.
  • Create a selector XML in res/drawable folder. The content of the selector XML checkbox_selector.xml is as below,
[java]&amp;amp;lt;?xml version="1.0" encoding="utf-8"?&amp;amp;gt;
&amp;amp;lt;selector xmlns:android="http://schemas.android.com/apk/res/android" &amp;amp;gt;
&amp;amp;lt;item android:state_enabled="false" android:drawable="@drawable/unchecked" /&amp;amp;gt;
&amp;amp;lt;item android:state_checked="true" android:drawable="@drawable/checked" /&amp;amp;gt;
&amp;amp;lt;item android:drawable="@drawable/unchecked" /&amp;amp;gt;
&amp;amp;lt;/selector&amp;amp;gt;
[/java]

The project structure with selector XML is as below,

  • Assign the selector to your CheckBox in your layout  – Unlike buttons, Checkboxes have a slightly different mechanism for changing the states. In case of CheckBox, the background is not associated with the state so assigning the selector to the checkbox is done through another attribute called android:button. The below is the code of the main.xml for creating custom checkbox.
[java]&amp;amp;lt;?xml version="1.0" encoding="utf-8"?&amp;amp;gt;
&amp;amp;lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" &amp;amp;gt;

&amp;amp;lt;TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dip"
android:text="CheckBox Demo"
android:textSize="18sp"
android:textStyle="bold" /&amp;amp;gt;

&amp;amp;lt;CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="CheckBox: Unchecked"
android:button="@drawable/checkbox_selector"
/&amp;amp;gt;
&amp;amp;lt;/RelativeLayout&amp;amp;gt;
[/java]

Now Run your code with the changes made to the project, The custom adapter is displayed as below,

Change the state of the checked, you can see the changed color of the checkbox drawable,

This is how you can create and use the standard and custom Checkbox in android. CheckBox can be added to AlerDialogs. To know more about how to add CheckBoxes to AlertDialogs, please refer the post AlertDialogCheckBox Hope this turorial served your purpose. Feel free to post your comments.

Filed Under: Google Android Tagged With: Android

Fragments in Android

May 21, 2013 by Krishna Srinivasan Leave a Comment

Fragments are like sub-activities which are objects that represent parts of an activity’s UI. Fragment is a modular section of an activity, which has its own lifecycle, receives its own input events. Multiple fragments can be combined to form a single activity to build multipane UI and reuse it as a single fragment in multiple activities. Fragment’s lifecycle is directly affected by the host activity’s lifecycle. If the host activity stops, all the fragments in it are stopped and when the host activity is destroyed, all fragments in to are destroyed. Fragments make it easier to adapt an application to different screen orientations and multiple screen sizes.

  • You must always embed a fragment in an activity. They can only exist within the context of an activity.
  • Fragments define their own layout, their own behaviour and their own life cycle.
  • You can insert a fragment into an activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element or You can add and remove fragments dynamically in an activity at runtime.
  • You can use fragments without its own UI as an invisible worker for the activity.
  • Inorder to acheive reusability, Fragment-to-Fragment communication should not be done. That is we should avoid direct manipulation of one fragment from another fragment.

Fragments introduced in Android 3.0( API level 11)

Android introduced fragments in Android 3.0. If you are using Android 3.0 or higher, then you are all set. You have access to the following,

  • Fragment class, which is the base class for all fragment definitions.
    android.app.Fragment
  • FragmentManager- which is the class for interacting with fragment objects inside the host Activity.
    android.app.FragmentManager
  • FragmentTransaction-which is the class for performing fragment transactions like as add, remove, or replace a fragment.
    android.app.FragmentTransaction

Android Compatibility Library(ACL)

Since Fragments were introduced for Android 3.0 and higher, Google has released the Android Compatibility Library(ACL) for Android 1.6 and higher. The ACL gives you access to the fragment system. Since ACL supports Android versions back to Android 1.6, Android 1.5 devices will not be able to use fragment system. If you are trying to build application using ACL on devices with Android 3.0 or higher, your application uses the class definitions from the Compatibility Package but not the device’s native implementation of the class. For more details on ACL, please refer to the Google documentation V4 library. When using compatibility library, you will need to subbclass FragmentActivity for any Activity that wants to make use of Fragment.

Why to use Fragments

Android runs on variety of devices like phones, tablets and large screen TVs. A Tablet has a large screen than does a phone. A TV has a larger screen than does a tablet. Fragments helps us to handle mutiple screen sizes. Lets assume we have an activity that displays a list of jobs(list of jobs) and details of each job if the user taps on any job in the list.
A tablet is more like a desktop, which has larger screen sizes. In this case, you can have the list of emails and the details of the selected email displaying on the same screen.

you can develop two fragment one for managing the list and another for managing the details of the list for this scenario, depending upon the screen size and change in the layout configurations the Fragments would be resued.

As you can see the picture used for tablets, the Activity A contains the Fragment A and Fragment B being displayed on the same screen. Fragment B updates when the selection is done on Fragment A. Whereas in Handsets because of its small size, the Activity A contains Fragment A which has list of emails, selecting an email in activity A, fires up a new activity named Activity B which has Fragment B displaying the details of the seletced email. This is how fragments helps in reusability while using devices of different size.

Fragments can also address the issue of orientation change. During the orientation change, Android re-creates your activity before switching to new orientation, wherein you have to save the current state of the activity and restore the state once the activity has been recreated. Using fragments you can retain a part of the UI which need not be altered, across orientation changes.

Fragment LifeCycle

Subclasses of Fragment class

Below are the subclasses of a Fragmnt Class

  • ListFragment
  • DialogFragment
  • PreferenceFragment
  • WebViewFragment

Creating a Fragment Class

To define a new fragment, you need to extend the Fragment class( android.app.Fragment) or one of the above mentioned subclasses of Fragment class. The below code shows how to define a fragment,

[java]public class FragmentListActivity extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.listlayout, container, false);
}
}[/java]

The above code will inflate the view R.layout.listlayout, and add it as a child view to the ViewGroup container. R.layout.listlayout is a simple layout file for your fragment class that you must have created in the path res/layout folder.

To provide a layout for the fragment, you must implement the onCreateview() callback method which returns a view(root of your fragment’s layout). The Android system invokes this method when it is time to put the Fragment on the screen. The arguments passed in to this callback include,

  1. layoutInflater which you can used to inflate a layout for this fragment.
  2. a ViewGroup parent
  3. Saved bundle

Filed Under: Google Android Tagged With: Android

What is StrictMode in Android? – Part 2

May 14, 2013 by Krishna Srinivasan Leave a Comment

In our previous post StrictMode Part 1  we had discussed how to set up StrictMode in development environment and how to run your application with StrictMode enabled on emulator. In this tutorial we would be discussing more about dealing with StrictMode. The main topics that we are going to discuss are,

  1. Turning off StrictMode When your application goes to production
  2. StrictMode with older versions of Android(prior to Android 2.3)
  • Buy: Hello, Android!!

Turning off StrictMode for Production purpose

I hope by now you have enough basic knowledge about what is StrictMode, how to enable it, and how to use it in production. Now we will discuss how to disable it when your application is ready to go on live failing which your application will crash on your users because of an alert. Below are the two ways by which you can disable StrictMode.

  •  Comment out or Remove the StrictMode code when your application finishes its building, testing and debugging stage.
  • You can use production flags to skip the StrictMode setup code when it is not needed.

If you start commenting out the StrictMode code, it would be difficult for you to continue development if anything else is left out in development. Hence the second approach to turnoff the StrictMode during production is better to use. This is done by simply declaring any flag and assigning it a boolean variable “true” in debugging mode and making it false once you are done with the development. You can make use of android:debuggable attribute that is present in AndroidManifest.xml for <application> Tag. Developer no longer need to add the android:debuggable attribute to the <application> tag in the manifest. The build tools add the attribute automatically. When exporting a signed release build, the tools do not add the attribute in the manifest. So it is enough for you to check whether android:debuggable attribute is true or false while setting up StrictMode.

Use the below code to check for debug mode,

[java]

// collects information from &lt;application&gt; tag
ApplicationInfo appInformation =context.getApplicationInfo();

//gives Flags associated with the application
int appFlags = appInformation.flags;

//Checks whether the application would like to allow debugging of its code
if ((appFlags &amp; ApplicationInfo.FLAG_DEBUGGABLE) != 0)
{
// StrictMode setup goes here
}[/java]

Above code checks for debug mode and performs the StrictMode set up accordingly.

StrictMode with older versions of Android(prior Android 2.3)

Lets assume we have an application targetting android 4.0(API 14) and minimum SDK version set to Android 2.2(API 8). I have made StrictMode enabled by using setThreadPolicy() and setVmPolicy() static methods. Now if you test your application on emulator of android 2.2(API 8), your application crashes by displaying ANR dialog. This is because StrictMode is not available in versions below Android 2.3. But your application works fine on Android 4.0 supporting emulators.
Lets see how can we get rid of this particular problem.

Create a separate method to deal with the older versions of Android( prior to Android 2.3) as below

[java]try {
//checks whether the strictMode class exists or what
Class class_obj = Class.forName("android.os.StrictMode");

//if the StrictMode class exists, the control comes here
Method enableDefaults = class_obj.getMethod("enableDefaults");

//dynamically invokes enableDefaults method which sets up StrictMode
enableDefaults.invoke(null);
}
catch(Exception e) {
// StrictMode not supported…
Log.v("STRICTMODE", " Lower version of android, StrictMode not supported");
}[/java]

As you can see in the above code, first you are checking whether android.os.StrictMode class is available or not. If it’s not, a ClassNotFoundException occurs which is caught by the catch block and we are writing a LogCat message by using Log class. You shouldn’t get any exceptions if StrictMode does exist, because enableDefaults() is one of its methods.The enableDefaults() method sets up StrictMode to detect everything and to write any violations to LogCat. If you run your application with this set up, on emulator supporting versions below Android 2.3, you get an Message logged in Logcat by your catch block and if you run on emulators supporting Android 2.3 and above, you will be alerted when you perform non-recommended things.

Another approach to deal with older versions of Android is using StrictMode wrapper class. This enables you to work with Higher and lower versions of Android while using StrictMode. If StrictMode is not available for your application, an
Error will be thrown if you try to access it. If you wrap StrictMode in a class and then catch the error, you can ignore when StrictMode is not available and get it when it is.

Lets us change the sample example that we have developed in our earlier post StrictMode Part 1. Add a StrictMode wrapper class to the project StrictModeTest by creating a class named StrictModeWrapper.java in the package my.app . the code of the StrictModeWrapper.java is as below.

[java]

package my.app;

import android.content.Context;
import android.os.StrictMode;

public class StrictModeWrapper {

public static void enableStrictMode(Context context) {
StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(
new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.build());
}
}[/java]

In the above code I have simply wrapped up the code of StrictMode set up that we have discussed in our earlier post, inside a enableStrictMode() static method.

Change the StrictModeTestActivity.java code to the below code.

[java]

package my.app;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

public class StrictModeTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Context context=StrictModeTestActivity.this;
//check whether debug mode is available
int applicationflags = context.getApplicationInfo().flags;
if ((applicationflags &amp; ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
//check whether the Android version is &gt;= 2.3.. if yes set up StrictMode by calling enableStrictMode() of wrapper class.
if (Build.VERSION.SDK_INT&gt;=Build.VERSION_CODES.GINGERBREAD) {
StrictModeWrapper.enableStrictMode(this);
}
else{
//If the android version is less than 2.3 log a message to LogCat
Log.v("VERSION &lt; Android 2.3", "StrictMode not supported");
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//Code to perform FILE I/O which will be caught by StrictMode
try {
OutputStreamWriter output_writer= new OutputStreamWriter(openFileOutput("FILETEST", MODE_WORLD_WRITEABLE));
BufferedWriter writer = new BufferedWriter(output_writer);
writer.write("Hi This is my File to test StrictMode");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}[/java]

In the above code we are just checking whether the SDK version is Android 2.3 or higher. If yes we would be calling enableStrictMode() method of the wrapper class, which sets up StrictMode. If your version is lesser tha Android 2.3 you are logging a error message to the LogCat.

Run your application on emulator supporting Android 4.0, you would get the below LogCat message while your Program runs well.

[java]02-15 16:25:04.665: D/StrictMode(929): StrictMode policy violation; ~duration=47 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=49 violation=1
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1048)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at libcore.io.BlockGuardOs.write(BlockGuardOs.java:178)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at libcore.io.IoBridge.write(IoBridge.java:447)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at java.io.FileOutputStream.write(FileOutputStream.java:187)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at java.io.OutputStreamWriter.flushBytes(OutputStreamWriter.java:167)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at java.io.OutputStreamWriter.close(OutputStreamWriter.java:140)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at java.io.BufferedWriter.close(BufferedWriter.java:98)
02-15 16:25:04.665: D/StrictMode(929): &nbsp;at my.app.StrictModeTestActivity.onCreate(StrictModeTestActivity.java:35)[/java]

Now run your application on emulator supporting Android 2.3 and see the LogCat entries. A log is being entered in LogCat where as the program runs well.

[java]02-15 18:16:21.905: V/VERSION &lt; Android 2.3(386): StrictMode not supported[/java]

This is how you can make your code run on all versions of Android with StrictMode enabled. Hope this tutorial helped you to work with StrictMode. If you have any queries, please post it in comments section.

  • Buy: Hello, Android!!

Filed Under: Google Android Tagged With: Android

What is StrictMode in Android? – Part 1

May 13, 2013 by Krishna Srinivasan Leave a Comment

StrictMode is a special class for verifying that your Android application is not doing things like disk I/O, Network access from the UI thread. This is a debugging feature introduced in Android 2.3. This developer tool detect things done accidentally and bring them to your attention so that you can fix them so as to avoid ANR dialogs(Activity Not Responding dialogs). StrictMode is used to setup thread and virtual machine policies for your application and report violations of such policies. You will get an alert if a policy is violated. You can instruct Android to crash your application with the alert or you can just log the alert and let your application carry on.

  • Buy: Hello, Android!!

StrictMode Policies

Currently there are two types of policies available with StrictMode.

  • Thread Policy.
  • VM(Virtual Machine) policy.

ThreadPolicy of StrictMode

Thread policies are concerned with the non-recommended things that are done on the main application thread(UI thread), notably flash I/O and Network I/O.

Violations you can look for using ThreadPolicy are,

  • Disk reads
  • Disk writes
  • Network accesss
  • Slow calls

The possible alerts that you can choose are,

  • Write to LogCat
  • Display a dialog
  • Flash the screen
  • write to the DropBox log file
  • Crash the application

Setting up StrictMode’s ThreadPolicy

The below code tells you how to set up StrictMode for thread policies,

[java]StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.penaltyLog() //Logs a message to LogCat
.build());[/java]

A good place to set policies is at the entry points to your application and activities. For instance, in a simple application, you may need to just put the code in the onCreate() method of the launch Activity class. setThreadPolicy is a static method so you don’t need to actually instantiate a StrictMode object. setThreadPolicy() method internally uses current thread for policy. The method bulid() returns a ThreadPolicy object. In the above code snippet, the policy is defined to alert on disk writes by logging the messages to LogCat. There are various detect and penalty methods available for ThreadPolicy which are listed below.

The various detect methods for Thread Policy are,

[java]detectDiskWrites() //API level 9
detectDiskReads() //API level 9
detectNetwork() //API level 9
detectCustomSlowCalls()//Introduced in API level 11[/java]

Instead of specific detect methods you can use detectAll() which detects all possible violations. detectCustomSlowCalls() is available from API level 11 using which you can detect slow code in your application.

The possible alerts(penalties) for thread policy are,

[java]penaltyLog() //Logs a message to LogCat
penaltyDeath() //Crashes application, runs at the end of all enabled penalties
penaltyDialog() //Show a dialog
penaltyDeathOnNetwork() //Crashes the whole process on any network usage
penaltyDropBox() //Enable detected violations log a stacktrace and timing data to the DropBox on policy violation
penaltyFlashScreen() //Introduced in API level 11 which Flash the screen during a violation[/java]

The above is the list of penalty methods available for ThreadPolicy. You can use two or more penalties while setting up the ThreadPolicy which will be executed based on priority. For example, you can make your system to Log your messages via penaltyLog() before crashing the process via penaltyDeath(). If no penalties are enabled before calling build, penaltyLog() is implicitly set.

VmPolicy of StrictMode

VM policy deals with bad coding practices resulting memory leaks like Detect leaks of Activity subclasses. Detects when SQLite object is finalized without having been closed or if any Closeable object is finalized before it has been closed. It is created via the same builder class as shown below.

[java]StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectActivityLeaks()
.detectLeakedClosableObjects()
.penaltyLog()
.build());[/java]

The possible policy violations for VmPolicy are,

[java]detectActivityLeaks() //API level 11. Detect leaks of Activity subclasses.
detectLeakedClosableObjects() //API level 11. Detect when an Closeable or other object with a explict termination method is finalized without having been closed.
detectLeakedSqlLiteObjects() //API level 9. Detect when an SQLiteCursor or other SQLite object is finalized without having been closed.
setClassInstanceLimit(Class.forName("my.app.sample.sampleclass"),10) //API level 11[/java]

setClassInstanceLimit(className, Limit) is introduced in API level 11 which Sets an upper bound on how many instances of a class can be in memory at once. Helps to prevent object leaks.

The penalties that are applicable for VmPolicy Violations are,

[java]
penaltyLog()
penaltyDeath()
penaltyDropBox()[/java]

Note most of the Penalties that I have listed for ThreadPolicy are not application for VmPolicy. For example, you cannot be alerted by showing a dialog if a VmPolicy is violated.

If you find any problematic violations, you can solve them using various approaches like threads and handlers , AsyncTask  atc. Don’t try to solve all violations that your StrictMode detects. For example, Sometimes the disk I/O is necessary in your activities Lifecycle. In such cases you have to temporarily allow your Activity to access the DISK.  Android provides some helper methods to make it easier to allow disk reads and writes from the main thread temporarily. Such helper methods are,

  • allowThreadDiskReads()
  • allowThreadDiskWrites()

allowThreadDiskWrites() permits both disk reads & writes. Whereas allowThreadDiskReads() permits only disk read. Use the below code to allow disk access.

[java]StrictMode.ThreadPolicy myoldpolicy=StrictMode.allowThreadDiskWrites();
//The code to write the DISK goes here
StrictMode.setThreadPolicy(myoldpolicy);[/java]

In the above code snippet,on line number 1 allowThreadDiskWrites() takes the current StrictMode.ThreadPolicy from getThreadPolic(), modifies it to permit both disk reads & writes, and sets the new policy with setThreadPolicy(StrictMode.ThreadPolicy), returning the old policy. Now “myoldpolicy” has the old StrictMode thread policy which is used to set the old policy again on line numer 3 after performing the nececcary Disk I/O. Note that There is no method for temporarily allowing network access.

So far we have learnt how to set up StrictMode for your application. Let us now study how to run your application with StrictMode. For that let us create a sample application, which has StrictMode enabled in it.

Step 1: Set up an Android working environment

If you are not familiar with setting up working environment for android, please follow the post Environment. For this example I would be using Android 4.0( API level 14).

Step 2: Create an Android Project

Create an android project named StrictModeTest with launcher activity StrictModeTestActivity. If you are not familiar with creating android projects, please follow one of our earlier posts Create a simple project.

Step 3: Create the required layouts

In this example, We would be using main.xml layout file. If you want to know more about layout files, please refer to the post Layouts in android. You need not to alter your main.xml file code for this example.

Step 4: Create required Activities

In this example, we would be using launcher activity StrictModeTestActivity.java. Open this and paste the below code,

[java]

package my.app;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;

public class StrictModeTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

//setThreadPolicy is a static method
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.penaltyLog() //Logs a message to LogCat
.penaltyDialog() //Shows a dialog
.build());

//VmPolicy
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectActivityLeaks()
.detectLeakedClosableObjects()
.penaltyLog()
.build());

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//Code to perform FILE I/O which will be caught by StrictMode
try {
OutputStreamWriter output_writer= new OutputStreamWriter(openFileOutput("FILETEST", MODE_WORLD_WRITEABLE));
BufferedWriter writer = new BufferedWriter(output_writer);
writer.write("Hi This is my File to test StrictMode");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

[/java]

Now you are done with setting up StrictMode for DiskWrites. In the above example you are trying to read and write the file. Hence you would be alerted by LogCat messages and via dialogs.

Step 4: Run your application

Select your project-> right click-> Run As-> Android Application

Now the Activity fires up with the Dialog which alerts saying, you are violating the StrictMode policies.

StrictMode is warning us that we are attempting  FILE write on application’s main thread. The same is being logged in LogCat since we have specified penaltyLog(). The LogCat stackTrace is as below.

[java]02-14 19:08:57.419: D/StrictMode(30397): StrictMode policy violation; ~duration=29 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=49 violation=1
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1048)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at libcore.io.BlockGuardOs.write(BlockGuardOs.java:178)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at libcore.io.IoBridge.write(IoBridge.java:447)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at java.io.FileOutputStream.write(FileOutputStream.java:187)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at java.io.OutputStreamWriter.flushBytes(OutputStreamWriter.java:167)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at java.io.OutputStreamWriter.close(OutputStreamWriter.java:140)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at java.io.BufferedWriter.close(BufferedWriter.java:98)
02-14 19:08:57.419: D/StrictMode(30397): &nbsp;at my.app.StrictModeTestActivity.onCreate(StrictModeTestActivity.java:34)[/java]

You can observe the above LogCat messages, on Line number 1 it is saying the StrictMode policy is violated.

Note:  Do not use StrictMode in production code. It is designed for use when you are building,
testing, and debugging your application.

  • Buy: Hello, Android!!

StrictMode was introduced in Android 2.3(API level 9) but more features were added in Android 3.0, so it is your duty to target the correct Android version and make sure your code is executed on the appropriate platforms. StrictMode is for android 2.3 and higher versions of android. Hence if in our application, the target API is 2.3 or higher and the MinSDK is below 9, this may crash your applications while testing on lower version emulator or devices.  We would be discussing how to support StrictMode in lower versions of android in our upcoming post StrictMode Part 2 . Stay Tuned. Hope this tutorial helped you to understand the usage of StrictMode. Please don’t forget to post your queries in comments section.

Filed Under: Google Android Tagged With: Android

AsyncTask in Android

May 12, 2013 by Krishna Srinivasan Leave a Comment

AsyncTask is an Helper class that allows you to perform background operations and updating the UI when the task completes. After the execution of the Background task, the results are published on the UI thread. It is ideal for running short operations that spans for few seconds. It serves better when compared to Threads and handlers since it enables proper and easy use of the UI thread.

  • Buy: Hello, Android!!

The AsyncTask class encapsulates the creation of Threads and Handlers. When an AsyncTask is created, it goes through 4 steps,

  • onPreExecute()
  • doInBackground(Params…)
  • onProgressUpdates(Progress…)
  • onPostExecute(Result)

The method doInBackgroung() executes automatically on a worker thread. The rest of the methods onPreExecute(), onPostExecute(), and onProgressUpdate() are all invoked on the UI thread. The value returned from the doInBackground() is sent to the onPostExecute() method. onProgressUpdate() method is executed by calling publishProgress() in doInBackground(). Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually. Overriding onPreExecute(), onPostExecute(Result), onProgressUpdate(Progress…) is optional.

AsyncTask is defined by three generic types Params, Progress, Result,

[java]class AsyncDemo extends AsyncTask&lt;Params, Progress, Result&gt; { … }&nbsp;[/java]

  • Params
    It is the type of the parameters passed in to the doInBackground.
  • Progress
    It is the type of the progress units published during the backgroung computation. These are passed in to the onProgressUpdate.
  • Result
    It is the return type of doInBackground and argument type passed in to onPostExecute.

An AsyncTask must be subclassed to be used as below,

[java]

private class AsyncDemo extends AsyncTask&lt;String, String, String&gt;{

@Override
protected void onPreExecute() {
// keeps the user informed about the long running tasks example by showing progressbar etc.
super.onPreExecute();
}

@Override
protected String doInBackground(String… params) {
// The code of long running tasks goes here
return null;
}

@Override
protected void onProgressUpdate(String… values) {
//when the long running tasks is in progress, the code to update the progress example updating the progress bar
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
//once the background work is done with execution, update the UI…
super.onPostExecute(result);
}
}[/java]

The above snippet shows how you can create An AsyncTask for your operations. Once created, the Task is executed using the below line,

[java]new AsyncDemo().execute();[/java]

While calling execute() method, pass the parameters which your AsyncTask is using.

Working of an AsyncTask

When an AsyncTask is executed by calling execute() method, it goes through 4 steps as stated above,

  1.  It first goes to onPreExecute() method, which is used to setup the Task. This can be used to keep the user informed about the Task that executes in background by showing a progressdialog.
  2. Then the control goes to doInBackground() method where the expensive work takes place. This is invoked immediately after onPreExecute() finishes executing. The parameters of the AsyncTask are passed(if any) to this method. The results are returned and are passed to the onPostExecute() method which processess the result and updates the UI accordingly if necessary.
  3. publishProgress(Progress…) can be called inside doInBackground() method which in turn calls the onProgressUpdate(Progress…) to publish one or more units of progress.
  4. After the backgroud task finishes its computation, onPostExecute(Result) is invoked. The Result of the background computation is passed as parameter to this step from the doInBackground(Params…) step. onPostExecute(Result) updates the UI(Example: Cancelling the ProgressDialog etc);

Let us now look at a simple example on how to execute long running tasks using AsyncTask

Working of the below AsyncTask example

In this example we would be displaying numbers in regular intervals of time forming a counterdown timer. The number of numerics to count is obtained from the user using an EditText. When the user clicks on a button called “Count”, the textview in the layout file starts showing numbers from 1 to any numeric specied by the user.(say 1 to 10 if your input is 10). When the numeric say 10 is displayed, the countdown stops and displays a message “Your countDown timer has stopped”.

Follow the below steps to create the example,

Step 1: Set up an android working environment

If you are not familiar with setting up the android environment, please refer to one of our earliar post, Environment. I would be using Android2.2 for this example.

Step 2 : Create an android project

Create a project named “AsyncTaskDemo” with the activity “ActivityAsyncTask”. If you are not familiar with creation of android project, please refer the post Create an Android project.

step 3: Create a layout

When you create your project, the layout main.xml gets created automatically. Here in this example we are going to use this main.xml layout file. Open your main.xml and paste the below code.

[java]&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="&lt;a href="http://schemas.android.com/apk/res/android"&gt;http://schemas.android.com/apk/res/android&lt;/a&gt;"&gt;
&lt;EditText android:id="@+id/EditText01" android:layout_height="wrap_content"
android:layout_width="90dip"&gt;&lt;/EditText&gt;
&lt;Button android:id="@+id/Button01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@+id/EditText01"
android:text="Count"&gt;&lt;/Button&gt;
&lt;TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true" android:textStyle="bold" android:textSize="18sp"&gt;&lt;/TextView&gt;
&lt;/RelativeLayout&gt;[/java]

Step 4: Create the required Activities

Here in this example I would be using the launcher activity ActivityAsyncTask.java. Open this activity and paste the below code,

[java]

package my.app;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ActivityAsyncTask extends Activity {
EditText input_time;
TextView count_textview;
Button start_count;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

start_count=(Button)findViewById(R.id.Button01);
count_textview=(TextView)findViewById(R.id.TextView01);
input_time=(EditText)findViewById(R.id.EditText01);

start_count.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//taking the input from the edittext
String input_number=input_time.getText().toString();
Integer input_time_int=Integer.parseInt(input_number);

//Starting CountDownStarterTask task by passing the parameter
new CountDownStarterTask().execute(input_time_int);
}
});
}

private class CountDownStarterTask extends AsyncTask&lt;Integer, Integer, Void&gt;{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Integer… params) {
// TODO Auto-generated method stub
for(int i=1;i&lt;=params[0].intValue();i++){
try {

//calls onProgressUpdate to publish the progress
publishProgress(i);
Thread.sleep(1000);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return null;
}
@Override
protected void onProgressUpdate(Integer… values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);

Integer time_to_set=values[0].intValue();
count_textview.setText(time_to_set.toString());
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
count_textview.setText("Your countDown timer has stopped");
}
}
}[/java]

As you can observe in the above code, we have an Edittext which collects the user input. You have to enter a numeric input and click on “Count” button. Which starts counting number from 1 to max number that you have given as input.

Step 5: Declaring the Activities in Android Manifest file

Your launcher activity is declared automatically. If you want to know more about android Manifest xml file, please refer to the post AndroidManifest.xml.

Your manifest file has the below code,

[java]

&lt;manifest xmlns:android="&lt;a href="http://schemas.android.com/apk/res/android"&gt;http://schemas.android.com/apk/res/android&lt;/a&gt;"
package="my.app"
android:versionCode="1"
android:versionName="1.0"&gt;
&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
&lt;activity android:name=".ActivityAsyncTask"
android:label="@string/app_name"&gt;
&lt;intent-filter&gt;
&lt;action android:name="android.intent.action.MAIN" /&gt;
&lt;category android:name="android.intent.category.LAUNCHER" /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;

&lt;/application&gt;
&lt;uses-sdk android:minSdkVersion="8" /&gt;
&lt;/manifest&gt;[/java]

Step 6: Run your App

Select your project-> Right click-> Run As-> Android Application

Activity ActivityAsyncTask fires up as below.

Enter a number of your choice(say 10) in the EditText and click on the button “Count”. Now the countDown starts as below.

When the count reaches 10 it stops and the below message appears on screen.

This is how you can make your long running tasks to run using AsyncTask without blocking the main UI thread. AsyncTask starting with DONUT was offering multitasking by using pool of threads whereas starting with HONEYCOMB, it uses single threading model. If you truly want parallel execution, you can always use executeOnExecutor(java.util.concurrent.Executor, Object[]) instead of execute(). Hope this tutorial helped you. Please post your queries, doubts if any in the comments section.

  • Buy: Hello, Android!!
  • Google Reference

Filed Under: Google Android Tagged With: Android

Threads and Handlers in Android

May 11, 2013 by Krishna Srinivasan Leave a Comment

When an android application is launched, a thread for that application is created by the system. This thread is called “main” or “UI thread”. Android uses single thread model ie. the system does not create a separate thread for each instance of a component. When you perform a long running task like database access, your UI thread can yield poor performance and these tasks will block the whole UI. Hence you can always create separate threads called worker threads to run your long running tasks.  All the UI updations should be done from the UI thread. Follow the below two rules while dealing with Android threads.

  1. Do not block the UI thread
  2. Do not access the Android UI toolkit from outside the UI thread.

Lets us now discuss how to make your application execute time consuming tasks without blocking the UI thread

Threading is used when your program executes time consuming  tasks(database access, calling web services etc.) with out blocking the UI thread. You can get away with blocking the UI thread using the following,

  • Thread with handlers
  • AsynTask

Creating a thread

The threads other than the Main UI thread are called as Worker threads. If you have operations to perform, that takes long time to complete, It is recommened to include them in worker threads. The worker threads are created using the below code snippet.

[java]&nbsp;&nbsp; new Thread(new Runnable() {
public void run() {
//time consuming tasks
}
}).start();[/java]

You can write the code of your long running tasks inside the run() callback. lets assume, I have an ImageView in my layout file. I want to download an image from the internet and upload that to the ImageView. I can add the code for downloading the image inside run() callback. Once the image from the internet is downloaded, I should set that image to the ImageView. Now the question is, Where will you write the code to update that ImageView?  Writing the code to update the ImageView inside run() method would not yield guaranteed result since you violet the second rule that we have already discussed, which says “Do not access the Android UI toolkit from outside the UI thread”. This can be solved by using handlers.

Handlers

Handlers are used to make updations to the UI in response to messages sent by threads running within the application’s process. Each handler instance is associated with the thread from which its been created and that thread’s message queue. Handlers are implemented in the main thread of an application. Handlers are used to send and process the following that are associated with the thread’s messagequeue. When a thread sends a message to the Handler it will get saved into a message queue and gets executed by the UI thread as soon as possible.

  • Messages
  • Runnable Objects

Let us look at the code snippet that tells how you can communicate with the handler using messages and Runnable Objects.

Communicating with the handler using Messages

This is done using the callback method handleMessage(Message msg) which is called when the messages are sent by the thread using the following methods

  • sendEmptyMessage(int)
  • sendMessage(Message)

Message sending can be scheduled and delayed by using the below methods,

  • sendEmptyMessageAtTime(int,long)
  • sendEmptyMessageDelayed(int,long)
  • sendMessageAtTime(Message,long)
  • sendMessageDelayed(Message,long)

Handler object is created and the run callback is used as below

[java]Handler handler = new Handler() {

//handles the thread’s messages and updates the UI
@Override
public void handleMessage(Message msg) {
//code to update the UI goes here….
}
};[/java]

The code that is used to update the user interface should be written inside the handleMessage() method which is called when the thread sends any messages to this handler. The worker thread which sends an empty message is created as below.

[java]

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

//starting a new thread on click of a button
new Thread(new Runnable() {
public void run() {
try {
/*long running tasks code is written here… I have made the thread to sleep for 4 seconds*/
Thread.sleep(4000);

//Sending an empty message to the handler indicating that the task has finished its execution
handler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}[/java]

As you can notice in the above code I have simply made the thread to sleep for 4 seconds so as to create an environment where the main thread has to wait for 4 seconds to get response from the worker thread. In your examples you can do any time consuming tasks like database access etc. in the place of this line. In the above snippet I have created a thread on click of a button which sends an empty message to the handler. Then the handler processes that message and updates the UI. Here I have just used a textview whose text changes when a thread sends the message to the handler.

[java]Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
txt.setText("text updated by worker thread");
}
};[/java]

In the above snippet, our worker thread has just sent an empty message to the handler. What if our thread wants to send any data to the handler? This is done using the method Message.setData(Bundle bundle), where Bundle object contains the data to be transfered. The code snippet for data transfer between thread and handler is as below.

[java]

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//starting a new thread on click of a button
new Thread(new Runnable() {
public void run() {
try {
/*long running tasks code is written here… I have made the thread to sleep for 4 seconds*/
Thread.sleep(4000);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("Message", "Data transfered");
msg.setData(bundle);
// send message to the handler
handler.sendMessage(msg);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}[/java]

The handler that processes the data sent by the worker thread is as below,

[java]Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// get the bundle and extract data by key
Bundle bundle = msg.getData();
String message = bundle.getString("Message");
txt.setText(message);
}
};[/java]

So far we have learnt how to communicate with the handler using messages. Lets us now look at how to communicate with the handler using Runnable Object.

Communicating with the handler using Runnable Object

You can use handlers by passing Runnable object to the handler.post() method. Use the below code snippet to use runnables,

[java]

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Runnable r=null;
//starting a new thread on click of a button
new Thread(new Runnable() {
public void run() {
try {
/*long running tasks code is written here… I have made the thread to sleep for 4 seconds*/
Thread.sleep(4000);

handler.post(r);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}[/java]

When you create any worker threads for your application to perform any time consuming tasks, it is recommended to keep the user informed saying that they will have to wait for sometime to get their work done. This is done by showing a progress dialog or a progress bar to the user. Please refer to the post ProgressDialog to know how to use threads and handlers in an application and how to keep the user informed about the background task. By using worker threads you can run time consuming tasks without blocking the User interface, however the long running tasks can be handled easily using AsyncTask. We would be discussing about AsyncTask in our next tutorial AsyncTask. Hope this tutorial helped you to understand the usage of Threads and handlers. Feel free to post your queries regarding this tutorial in comments section.

  •  

Filed Under: Google Android Tagged With: Android

How to create ProgressDialog in android?

May 10, 2013 by Krishna Srinivasan Leave a Comment

Android Progress Dialog is an extension of the AlertDialog class that can display a spinner wheel or a progress bar. These dialogs help us to inform the users about the time consuming tasks and keep them involved till they get their work done. Android progress dialog can be of two types.

  1. ProgressDialog with a horizontal progress bar.
  2. ProgressDialog with a ciruclar, spinning progress bar.

A ProgressDialog with a Spinner wheel looks like the below screen.

These ProgressDialogs can have buttons too(Example: to cancel a download progress). The dialog can be made cancelable on back key press.

This tutorial demostrates how you can create a simple ProgressDialog with the Spinning Wheel.

Creating a ProgressDialog with circular spinning wheel

The Spinning wheel ProgressDialog  is often used when your long running task takes undefined time or its time of completion is not known.

A progress dialog can be opened by calling ProgressDialog.show(). This can be easily done without managing the dialog inside onCreateDialog() callback as used in the post AlertDialog while creating an AlertDialog which has lists,Checkboxes and RadioButtons.

The syntax of ProgressDialog.show() is as below.

[java]ProgressDialog.show(ActivityProgressDialog.this,
&amp;quot;Please wait&amp;quot;, &amp;quot;Your result is being calculated&amp;quot;, true);[/java]

where the first parameter represents the context, second represents the title, third is the message and the last parameter tells whether the ProgressDialod is indeterminate or not. We have passed true since we are creating a spinning wheel ProgressDialog. The default style of the ProgressDialog is Spinning Wheel. Hence you can use the show() method without the last parameter.

Let us now discuss a simple example which explains the steps to create a Spinning wheel Progress Dialog.

In this example we are building a result calculation system. When the user clicks on the submit button, a ProgressDialog is shown, which asks him to wait till the result is being calculated. Then the result is shown to the user. Here the emphasis is more on creating a ProgressDialog and not on result calculation. Hence the “score” String is hardcoded with some value to display it to the user.

Step 1: Set up the android working environment

If you are not familiar with setting up an android environment, please have a look at the post, Environment. This example is built using API level 8.

Step 2: Create an Android Project

Create an android project named ProgressDialogDemo with the launcher activity ActivityProgressDialog.java. If you are not familiar with the android project creation, please refer to the post Simple android project.

Step 3: Create the required layouts

In this example, We would be using main.xml layout file. If you want to know more about layout files, please refer to the post Layouts. Open the main.xml file and paste the below code.

[java]
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;RelativeLayout android:id=&amp;quot;@+id/RelativeLayout01&amp;quot;
android:layout_width=&amp;quot;fill_parent&amp;quot; android:layout_height=&amp;quot;fill_parent&amp;quot;
xmlns:android=&amp;quot;&amp;lt;a href=&amp;quot;http://schemas.android.com/apk/res/android&amp;quot;&amp;gt;
http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;&gt;
&amp;lt;TextView android:id=&amp;quot;@+id/TextView01&amp;quot; android:layout_width=&amp;quot;wrap_content&amp;quot;
android:layout_height=&amp;quot;wrap_content&amp;quot; android:text=&amp;quot;Press Submit button to get your results&amp;quot;
android:layout_centerHorizontal=&amp;quot;true&amp;quot; android:textStyle=&amp;quot;bold&amp;quot;
android:textSize=&amp;quot;15sp&amp;quot; android:layout_marginTop=&amp;quot;30dip&amp;quot;&amp;gt;&amp;lt;/TextView&amp;gt;

&amp;lt;Button android:id=&amp;quot;@+id/Button01&amp;quot; android:layout_below=&amp;quot;@id/TextView01&amp;quot;
android:layout_width=&amp;quot;wrap_content&amp;quot; android:layout_height=&amp;quot;wrap_content&amp;quot;
android:layout_centerHorizontal=&amp;quot;true&amp;quot; android:text=&amp;quot;Submit&amp;quot;
android:layout_marginTop=&amp;quot;15dip&amp;quot;&amp;gt;&amp;lt;/Button&amp;gt;

&amp;lt;TextView android:id=&amp;quot;@+id/TextView02&amp;quot; android:layout_below=&amp;quot;@id/Button01&amp;quot;
android:layout_width=&amp;quot;wrap_content&amp;quot; android:layout_height=&amp;quot;wrap_content&amp;quot;
android:layout_centerHorizontal=&amp;quot;true&amp;quot; android:visibility=&amp;quot;gone&amp;quot;
android:textSize=&amp;quot;16sp&amp;quot; android:textStyle=&amp;quot;bold&amp;quot;
android:text=&amp;quot;congratulations!! Your score is &amp;quot;&amp;gt;&amp;lt;/TextView&amp;gt;
&amp;lt;/RelativeLayout&amp;gt;[/java]

The main.xml has a “Submit” button which triggers a ProgressDialog. It has 2 textviews.The first one is Textview01, which tells the user to click “Submit” button. Textview02 is made invisible in the beginning.

Step 4: Create the required Activities

Here in this example, we would be using launcher activity ActivityProgressDialog.java. Open ActivityProgressDialog.java and paste the below code.

[java]

package my.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ActivityProgressDialog extends Activity {
ProgressDialog progressdialog;
Button Spinner_progress, Progress_bar;
ProgressDialog progressbar;
Handler mHandler;
TextView instruction,marks_update;
String score;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Spinner_progress=(Button)findViewById(R.id.Button01);
instruction=(TextView)findViewById(R.id.TextView01);
marks_update=(TextView)findViewById(R.id.TextView02);
Spinner_progress.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressdialog=ProgressDialog.show(ActivityProgressDialog.this,
&amp;quot;Please wait&amp;quot;, &amp;quot;Your score is being calculated&amp;quot;);

//creating a separate thread
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getResults();
}
}).start();

mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 10:
progressdialog.dismiss();
marks_update.setVisibility(View.VISIBLE);
marks_update.append(score);
instruction.setVisibility(View.GONE);
Spinner_progress.setVisibility(View.GONE);

break;
}
}
};

}
});
}
private void getResults() {
// TODO Auto-generated method stub
try {
/*Write the code of your long
*running tasks here*/

//assigned 80% to score string, to display the results
score=&amp;quot;80%&amp;quot;;

mHandler.sendEmptyMessage(10);

} catch (Exception e) {
// TODO: handle exception
mHandler.sendEmptyMessage(1);
}
}

}[/java]

Let us now try to understand the flow of the above code. In the onCreate() function we create the ProgressDialog on click of the button “submit” using the method ProgressDialog.show(). As you can notice, we have created a separate thread to calculate the result. when the thread.start() is executed, it creates a new thread and executes the run() function, which inturn calls the method getResults(). Before calling getResults() I have made the thread to sleep for some time. This is done to make the ProgressDialog visible for more time.

The getResults() method calculates your score(does long running tasks in other case) and sends an Empty message to the handler. Sometimes its difficult to update the UI when you are running separate threads hence here we use handlers to update the UI. When the handler receives the message, it dismisses the ProgressDialog and does the UI updations.

Step 5: Declare the activities in AndroidManifest.xml

Your launcher activity is declared automatically. If you want to know more about AndroidManifest.xml file, please refer to our earlier post, Manifest.

Your Manifest file has the below code.

[java]

&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;manifest xmlns:android=&amp;quot;&amp;lt;a href=&amp;quot;http://schemas.android.com/apk/res/android&amp;quot;&amp;gt;
http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;
package=&amp;quot;my.app&amp;quot;
android:versionCode=&amp;quot;1&amp;quot;
android:versionName=&amp;quot;1.0&amp;quot;&amp;gt;
&amp;lt;application android:icon=&amp;quot;@drawable/icon&amp;quot; android:label=&amp;quot;@string/app_name&amp;quot;&amp;gt;
&amp;lt;activity android:name=&amp;quot;.ActivityProgressDialog&amp;quot;
android:label=&amp;quot;@string/app_name&amp;quot;&amp;gt;
&amp;lt;intent-filter&amp;gt;
&amp;lt;action android:name=&amp;quot;android.intent.action.MAIN&amp;quot; /&amp;gt;
&amp;lt;category android:name=&amp;quot;android.intent.category.LAUNCHER&amp;quot; /&amp;gt;
&amp;lt;/intent-filter&amp;gt;
&amp;lt;/activity&amp;gt;

&amp;lt;/application&amp;gt;
&amp;lt;uses-sdk android:minSdkVersion=&amp;quot;8&amp;quot; /&amp;gt;

&amp;lt;/manifest&amp;gt;[/java]

Step 6: Run your project

Select your project->right click->Run As->Android Application.

Press the submit button to see your progress Dialog.

Then the score displays as below.

Filed Under: Google Android Tagged With: Android

How to add lists, Checkboxes and Radio buttons to an AlertDialog – Android

May 7, 2013 by Krishna Srinivasan Leave a Comment

A Dialog is a small window that appears in front of the current Activity.  An AlertDialog is a Dialog which can have zero, one, two or three buttons. We have discussed about creating a simple AlertDialog in one of our earlier posts AlertDialog.  The previous tutorial on AlertDialog demonstrated how to create an AlertDialog which has  title, simple message and buttons.  This tutorial demonstrates how to add lists, CheckBoxes and Radio Buttons to an AlertDialog.

Prerequisites:

You must have enough knowledge on how to create an AlertDialog. If you are not familiar with creating an AlertDialog, please refer to the post Create an AlertDialog .Unlike the previous post, here in this tutorial we would be using  few methods of the Activity

  • onCreateDialog()
  • onPrepareDialog()
  • showDialog()

When you want to show a dialog, call showDialog(int) method and pass in an integer variable that uniquely identifies your dialog.
When the dialog is requested for the first time, Android calls onCreateDialog(int) from your Activity. You should instantiate your dialog inside onCreateDialog method. This callback returns the Dialog object.

If you want to do change any properties of your dialog each time it is opened, you can make use of an optional callback onPrepareDialog(int,dialog), which is called every time your dialog is opened whereas onCreateDialog(int) is only called for the very first time your dialog is opened. If you donot define onPrepareDialog method, your dialog’s selection state remains unchanged(such as items checked in the checkbox or radio button remains checked even when the dialog is opened for the second time).

Your job is to call the method showDialog with the unique integer that identifies your dialog. Android calls the rest of the methods onCreateDialog and onPrepareDialog.

It is recommended to use switch statement inside onCreateDialog and onPrepareDialog callbacks that checks the id parameter that is passed as parameters to these methods and creates the dialog accordingly.

[java]
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case LIST_ALERTDIALOG:

break;
case CHECKBOX_ALERTDIALOG:

break;
case RADIOBUTTON_ALERTDIALOG:

break;

}
return null;
}[/java]

Creating an AlertDialog with a list of items

1_Alertpost2

Above is the picture of an AlertDialog with a list of items. To create an AlertDialog with a list of selectable items, use the method setItems().

[java]public AlertDialog.Builder setItems (CharSequence[] items,
DialogInterface.OnClickListener listener);[/java]

The setItems() method takes 2 parameters, first one is the list of items to be displayed in the dialog as its content and the next is the listener which notifies about the selected item.

When you call showDialog(LIST_ALERTDIALOG) method, where LIST_ALERTDIALOG is the variable representing your list AlertDilaog, Android calls the onCreateDialog(LIST_ALERTDIALOG) where in it goes to the first case statement which matches your List AlertDialog. The below code snippet is used to define and create your dialog inside the first case .

[java]
case LIST_ALERTDIALOG:

AlertDialog.Builder builder=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle("Choose a Color")
.setItems(colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"The selected color is "+colors_list[which], Toast.LENGTH_LONG).show();
}
});
AlertDialog alertdialog=builder.create();
return alertdialog;[/java]

In the above code colors_list is the array of items to display.

[java]final CharSequence[] colors_list={"Green","Black","White"};[/java]

Here in the case statement, we are displaying a Toast message on click of a list item. The toast displays the selected item. If you want more information about how to create a toast message, please go through the post Toast . Finally the case statement returns the Dialog object.

Note: Few lines in the above case statement are not explained here, since it has been covered in one of our previous posts.  Please refer to the post How to create an AlertDialog to know how to create a simple Alertdialog.

Creating an AlertDialog with Checkboxes

Now we would be discussing about the second case statement “case CHECKBOX_ALERTDIALOG:” An AlertDialog with checkBoxes is as shown below.

2_check

As you can see in the above screen of alertDialog, I have added a button “OK” to get the checked item details. However adding “OK” button is optional.

To create an AlertDialog with a list of multiple-choice items, you have to make use of the method setMultiChoiceItems(). The code is as same as the previous code snippet, but setItems() method is replaced with the setMultiChoiceItems() method. This method takes 3 parameters. The syntax of the method setMultiChoiceItems() is as below.

[java]public AlertDialog.Builder setMultiChoiceItems (CharSequence[] items,
boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener);
[/java]

First parameter is the text of the items to be displayed in the list, second parameter specifies which items are checked. It should be null in which case no items are checked. If non null it must be exactly the same length as the array of items. you will be notified of the selected item via the supplied listener as the third parameter. Clicking on an item in the list will not dismiss the dialog hence I have added a button “OK” which takes the items that you have checked and dismisses the dialog on click of it.

Creating an AlertDialog with RadioButtons

The alertDialog with a list of single-choice items is as shown below.

3_radio

We have to use setSingleChoiceItems() method to create such AlertDialogs. This method takes three parameters. The syntax is as below.

[java]public AlertDialog.Builder setSingleChoiceItems (CharSequence[] items,
int checkedItem, DialogInterface.OnClickListener listener);[/java]

First parameter is the list of items to be displayed. Second is the “checkedItem”  specifies which item is checked. If -1 no items are checked. The third parameter is a “listener”  notified when an item on the list is clicked. The dialog will not be dismissed when an item is clicked.

Add the below code to the third case statement of the onCreateDialog method to create an AlertDialog with radiobuttons.

[java]

case RADIOBUTTON_ALERTDIALOG:

AlertDialog.Builder builder2=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle("Choose a Color")
.setSingleChoiceItems(colors_radio, -1, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"The selected color is "+colors_radio[which], Toast.LENGTH_LONG).show();

//dismissing the dialog when the user makes a selection.
dialog.dismiss();
}
});
AlertDialog alertdialog2=builder2.create();
return alertdialog2;[/java]

As you see in the above code, We have used dialog.dismiss inside onclick() of the list since clicking on the list item do not dismisses the dialog. colors_radio is the list of items to be displayed.

[java]final CharSequence[] colors_radio={"Green","Black","White"};[/java]

If you create any one of the above selectable lists(checkbox or radiobuttons) in the onCreateDialog() callback method, the state of the selected item is managed by Android as long as the Activity is active.

So far we have seen details on AlertDialog with lists, CheckBoxes and RadioButtons. Let us now learn how to create a project which has all these types of dialogs.

Required layouts

  • main.xml which has three buttons namely “List”(shows a List AlertDialog), “CheckBox” and “RadioButton”.

Required Activity

  • AlertDialogDemo

Step 1: Set up the android developement evvironment

This topic has already been discussed in one of our previous posts Environment. Please refer the post for more queries. I would be using Android 2.2 for this example.

Step 2: Create the Project

Create a project named “AlertDialog” with the launcher activity AlertDialogDemo.java. For more information on how to create a new project in android, please refer to the post Create an android project.

Step 3: Create the required layouts

As i said earlier, I would be using main.xml layout file. To know more about layout xml files, please go through the post Layouts. Open the main.xml file and paste the below code.

[java]

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="<a href="http://schemas.android.com/apk/res/android">
http://schemas.android.com/apk/res/android</a>">
<Button android:id="@+id/Button01" android:layout_height="wrap_content"
android:text="List" android:layout_width="90dip"
android:layout_marginLeft="20dip" android:layout_centerVertical="true"></Button>
<Button android:id="@+id/Button02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@+id/Button01"
android:text="CheckBox" android:layout_centerVertical="true"></Button>
<Button android:id="@+id/Button03" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@+id/Button02"
android:text="RadioButton" android:layout_centerVertical="true"></Button>
</RelativeLayout>[/java]

As you can notice, I have used three buttons to trigger your three AlertDilaogs.

Step 4: Create the required Activities

Here in this example, I would be using the launcher activity “AlertDialogdemo”. Open the activity and paste the below code.

[java]

package my.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class AlertDialogDemo extends Activity implements OnClickListener {
/** Called when the activity is first created. */

final int LIST_ALERTDIALOG=0,CHECKBOX_ALERTDIALOG=1,RADIOBUTTON_ALERTDIALOG=2;
final boolean checked_state[]={false,false,false}; //The array that holds the checked state of the checkbox items
final CharSequence[] colors_check={"Green","Black","White"}; //items in the alertdialog that displays checkboxes
final CharSequence[] colors_list={"Green","Black","White"}; //items in the alertdialog that displays list
final CharSequence[] colors_radio={"Green","Black","White"}; //items in the alertdialog that displays radiobuttons
Button list,check,radio;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

list=(Button)findViewById(R.id.Button01);
check=(Button)findViewById(R.id.Button02);
radio=(Button)findViewById(R.id.Button03);

list.setOnClickListener(this);
check.setOnClickListener(this);
radio.setOnClickListener(this);
}

/*triggered by showDialog method. onCreateDialog creates a dialog*/
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case LIST_ALERTDIALOG:

AlertDialog.Builder builder=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle("Choose a Color")
.setItems(colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "The selected color is "+colors_list[which], Toast.LENGTH_LONG).show();
}
});
AlertDialog alertdialog=builder.create();
return alertdialog;

case CHECKBOX_ALERTDIALOG:

AlertDialog.Builder builder1=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle("Choose a Color")
.setMultiChoiceItems(colors_check, null, new DialogInterface.OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub

//storing the checked state of the items in an array
checked_state[which]=isChecked;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String display_checked_colors = "";
for(int i=0;i<3;i++){
if(checked_state[i]==true){
display_checked_colors=display_checked_colors+" "+colors_check[i];
}
}
Toast.makeText(getApplicationContext(), "The selected color(s) is
"+display_checked_colors, Toast.LENGTH_LONG).show();

//clears the String used to store the displayed text
display_checked_colors=null;

//clears the array used to store checked state
for(int i=0;i<checked_state.length;i++){
if(checked_state[i]==true){
checked_state[i]=false;
}
}

//used to dismiss the dialog upon user selection.
dialog.dismiss();
}
});
AlertDialog alertdialog1=builder1.create();
return alertdialog1;

case RADIOBUTTON_ALERTDIALOG:

AlertDialog.Builder builder2=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle("Choose a Color")
.setSingleChoiceItems(colors_radio, -1, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"The selected color is "+colors_radio[which], Toast.LENGTH_LONG).show();

//dismissing the dialog when the user makes a selection.
dialog.dismiss();
}
});
AlertDialog alertdialog2=builder2.create();
return alertdialog2;
}
return null;

}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub

switch (id) {
case CHECKBOX_ALERTDIALOG:
AlertDialog prepare_checkbox_dialog=(AlertDialog)dialog;
ListView list_checkbox=prepare_checkbox_dialog.getListView();
for(int i=0;i<list_checkbox.getCount();i++){
list_checkbox.setItemChecked(i, false);
}
break;
case RADIOBUTTON_ALERTDIALOG:
AlertDialog prepare_radio_dialog=(AlertDialog)dialog;
ListView list_radio=prepare_radio_dialog.getListView();
for(int i=0;i<list_radio.getCount();i++){
list_radio.setItemChecked(i, false);
}
break;

}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch (v.getId()) {
case R.id.Button01:
//triggering the List alertdialog
showDialog(LIST_ALERTDIALOG);
break;
case R.id.Button02:
//triggering the checkbox alertdialog
showDialog(CHECKBOX_ALERTDIALOG);
break;
case R.id.Button03:
//triggering the radio alertdialog
showDialog(RADIOBUTTON_ALERTDIALOG);
break;

default:
break;
}

}
}[/java]

I have used onPrepareDialog() method to change the selection state of the selected list items. Since Android manages the state of the selectable list, doing this is recommended.

Step 5: Declare the activities in AndroidManifest.xml

Your launcher activity is registered automatically. If you want to know more on Manifest file, please follow the post on Manifest. Your AndroidManifest.xml has the below code.

[java]

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="<a href="http://schemas.android.com/apk/res/android">
http://schemas.android.com/apk/res/android</a>"
package="my.app"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AlertDialogDemo"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>[/java]

Step 6: Run your Project

Select your project->Right click->Run As->Android Application. Your first activity pops up as below.

4_alertout1

your activity is displaying three buttons. Click on the button “List” which displays your first AlertDialog with List of items “Green”, “Black” and “White” as below.

Select any one of the item from the list displayed inside your AlertDialog. I would be selecting “Black” from the list. You will get a Toast message showing the selected item as below.

5_alertout3

Now click on the button “CheckBox”, It displays an AlertDialog with list having checkBoxes.

6_alertout4

Select any number of items and click on “OK”. The checked items are displayed in the toast as below.

6_alertout4

Click the button “RadioButton” which displays the Dialog with list having radioButtons.

8_alertout6

select any item. The AlertDialog is closed and a toast is displayed showing the checked item name.

9_alertout7

This is how you can create AlertDialog with different content areas. If you have any queries, please post it in comments section.

Filed Under: Google Android Tagged With: Android

  • 1
  • 2
  • 3
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved