Unit Iv
Unit Iv
Using List View, Using the Spinner control, Using the GridView Control, Creating anImage Gallery
Using the ViewPager Control
Using the Debugging Tool:Dalvik DebugMonitor Service(DDMS), Debugging Application, Using
the Debug Perspective.
Displaying And Fetching Information Using Dialogs and Fragments: What AreDialogs?, Selecting
the Date and Time in One Application, Fragments, CreatingFragments with java Code, Creating
Special Fragments
Android ListView
Android ListView is a view which contains the group of items and displays in a scrollable list.
ListView uses Adapter classes which add the content from data source (such as string array, array,
database etc) to ListView. Adapter bridges data between an AdapterViews and other Views (ListView,
ScrollView etc).
Example of ListView
Let's implement a simple listview example.
Page 1
Mobile Application Development Unit-IV
activity_main.xml
First we need to drag and drop ListView component from palette to activity_main.xml file.
File: activity_main.xml
Create an additional mylist.xml file in layout folder which contains view components displayed in
listview.
File: mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<TextViewxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d"
/>
Now place the list of data in strings.xml file by creating string-array.
strings.xml
File:strings.xml
<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>Android</item>
<item>Java</item>
<item>Php</item>
<item>Hadoop</item>
<item>Sap</item>
Page 2
Mobile Application Development Unit-IV
<item>Python</item>
<item>Ajax</item>
<item>C++</item>
<item>Ruby</item>
<item>Rails</item>
<item>.Net</item>
<item>Perl</item>
</string-array>
</resources>
Activity class
In java class we need to add adapter to listview using setAdapter() method of listview.
File: MainActivity.java
package in.kvsw.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
listView=(ListView)findViewById(R.id.listView);
textView=(TextView)findViewById(R.id.textView);
listItem= getResources().getStringArray(R.array.array_technology);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?>adapterView, View view, intposition, long l)
{
// TODO Auto-generated method stub
String value=adapter.getItem(position);
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}
});
}
}
Page 3
Mobile Application Development Unit-IV
Output
Spinner Control
Android Spinner is like the combo box of AWT or Swing. It can be used to display the multiple options
to the user in which only one item can be selected by the user.
Android spinner is like the drop down menu with multiple values from which the end user can select only
one value.
Android spinner is associated with AdapterView. So you need to use one of the adapter classes with
spinner.
Android Spinner class is the subclass of AbsSpinner class.
In this Application, we are going to display the country list. You need to use ArrayAdapter class to store
the country list.
Let's see the simple example of spinner in android.
activity_main.xml
Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.andro
id.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
Page 4
Mobile Application Development Unit-IV
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.spinner.MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />
</android.support.constraint.ConstraintLayout>
Activity class
Let's write the code to display item on the spinner and perform event handling.
File: MainActivity.java
package in.kvsw.spinner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
Page 5
Mobile Application Development Unit-IV
Page 6
Mobile Application Development Unit-IV
As the name suggests, ViewGroup is a view that contains other views known as child views.
The ViewGroup class is a base class for layout managers that are used to contain and arrange several
views. ListView, GridView, and other container controls are good examples of ViewGroups.
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextViewandroid:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select a fruit " />
<GridViewandroid:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:columnWidth="130dip"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout>
Page 7
Mobile Application Development Unit-IV
Page 8
Mobile Application Development Unit-IV
In the upper-left pane of the DDMS window, we see a Devices tab that displays the list of Android
devices connected to your PC, along with the running AVDs (if any). The VMs associated with each
device or AVD also is displayed. Selecting a VM displays its information in the right pane. In
the Devices tab, you see some icons, described here:
• Debug—Used to debug the selected process.
• Update Heap—Enables heap information of the process. After clicking this icon, use the Heap icon on
the right pane to get heap information.
• Dump HPROF file—Shows the HPROF file that can be used for detecting memory leaks.
• Cause GC—Invokes Garbage Collection.
Page 9
Mobile Application Development Unit-IV
• Update Threads—Enables fetching the thread information of the selected process. After clicking this
icon, we need to click the Threads icon in the right pane to display information about the threads that are
created and destroyed in the selected process.
• Start Method Profiling—Used to find the number of times different methods are called in an
application and the time consumed in each of them. Click the Start Method Profiling icon, interact with
the application, and click the Stop Method Profiling icon to obtain information related to the different
methods called in the application.
• Stop Process—Stops the selected process.
• Screen Capture—Captures our device/emulator screen. If the application is running and its output is
being displayed through the device/emulator, clicking the Screen Capture icon displays the Device Screen
Capture dialog box, as shown in Figure-(left). The text, Capturing, tells us that the output of the
application or image being displayed in the device/emulator is in the process of being captured. Once the
image is captured, it is displayed as shown in Figure-(right).
Image shown in the device/emulator is being captured (left), and the captured image of the
device/emulator displayed (right)
The meaning of the buttons shown at the top in the Device Screen Capture dialog box is shown here:
• Refresh—Updates the captured image.
• Rotate—With each click of this button, the captured image rotates 90 degrees in the counterclockwise
direction.
• Save—Saves the captured image as a .png file.
• Copy—Copies the captured image to the clipboard.
• Done—Closes the Device Screen Capture dialog.
Back to DDMS, on the right pane (refer above Figure), we find the following tabs:
• Threads—Displays information about the threads within each process, as shown in above Figure (left).
The following information about the threads is displayed:
• Thread ID—Displays the unique ID assigned to each thread
• Status—Displays the current status of the thread—whether it is in running, sleeping, starting, waiting,
native, monitor, or zombie state
• utime—Indicates the cumulative time spent executing user code
Page 10
Mobile Application Development Unit-IV
The Threads tab, displaying information about running threads (left), and the Heap tab displaying heap
information of the current process (right)
• Allocation Tracker—Tracks the objects allocated to an application. Click the Start Trackingbutton,
interact with the application, and then click Get Allocations to see the list of objects allocated to the
application (see Figure—left). After we click the Get Allocations button again, the newly allocated
objects are added to the earlier displayed list of allocated objects. We can also click the Stop
Tracking button to clear the data and restart.
The Allocation Tracker tab, which tracks objects allocated to the application (left) and the File
Explorer tab, displaying the file system on the device/emulator (right)
• Network Statistics—Helps us in getting information regarding network usage of our application, that
is, when our app made network requests, speed of data transfer—and other related information.
• File Explorer—Displays the file system on the device, as shown in Figure (right). We can view and
delete files on the device/emulator through this tab. We can even push or pull files from the device using
the two icons, Pull a file from the device and Push a file onto the device, that are shown at the top. To
copy a file from the device, select the file in the File Explorer and click the Pull a file from the
device button. The Get Device File dialog box opens up, prompting us to specify the path and filename
where we want to store the pulled device file. Similarly, to copy a file to the device, click the Push file
onto the device button in the File Explorer tab. The Put File on Device dialog box opens up, letting us
browse the local disk drive. Select the file we want to copy to the device and click Open button to copy it
to the device.
Page 11
Mobile Application Development Unit-IV
Right of the File Explorer tab is the Emulator Control tab that can be used to simulate incoming phone
calls, SMS messages, or GPS coordinates. To simulate an incoming phone call, select the Voice option,
provide the incoming phone number, and click the Call button, as shown in Figure (left). In the emulator,
an incoming call appears, prompting the user to answer the call in Figure (right). The incoming call can
be ended either by clicking the End button in the emulator or by clicking the Hang Up button in
the Emulator Control tab.
Simulating an incoming phone call through the Emulator Control tab (left), and an incoming phone call
appears on the Android emulator (right).
To simulate an SMS message, select the SMS option in the Emulator Control tab, provide the phone
number, write the message, and click the Send button, as shown in Figure(left). In the emulator, an
incoming SMS notification appears at the top (see Figure—right). We can simulate GPS coordinates
(longitude and latitude values) manually, via the GPX file or KML file through the Emulator Control tab.
Remember, only GPX 1.1 files are supported.
Simulating SMS via the Emulator Control tab (left), and incoming SMS notification displayed at the top
in the Android emulator (right)
The bottom pane of the DDMS is used to show the log of the processes on the selected device or AVD.
The pane is meant for performing debugging and tracing tasks. The LogCat tab shows all messages of the
device, including exceptions and those placed in the application to see the intermediate results. We can
also set up filters to watch filtered log information. The Console tab displays the messages related to the
starting of the activity.
Page 12
Mobile Application Development Unit-IV
Page 13
Mobile Application Development Unit-IV
AlertDialog
An AlertDialog is a popular method of getting feedback from the user. This pop-up dialog remains there
until closed by the user and hence is used for showing critical messages that need immediate attention or
to get essential feedback before proceeding further.
The simplest way to construct an AlertDialog is to use the static inner class AlertDialog.Builder that
offers a series of methods to configure an AlertDialog.
Page 14
Mobile Application Development Unit-IV
Page 15
Mobile Application Development Unit-IV
<TextViewandroid:id="@+id/datetimevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button android:id="@+id/date_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Date" />
<Button android:id="@+id/time_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Time" />
</LinearLayout>
MainActivity.java
package in.kvsw.dateandtime;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.TimePicker;
import android.widget.DatePicker;
Page 16
Mobile Application Development Unit-IV
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTimeView= (TextView) findViewById(R.id.datetimevw);
Button timeButton = (Button) findViewById(R.id.time_button);
Button dateButton = (Button) findViewById(R.id.date_button);
c = Calendar.getInstance();
h = c.get(Calendar.HOUR_OF_DAY);
m = c.get(Calendar.MINUTE);
yr= c.get(Calendar.YEAR);
mon= c.get(Calendar.MONTH);
dy= c.get(Calendar.DAY_OF_MONTH);
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and current
time is: "+h+":"+m);
dateButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new DatePickerDialog(MainActivity.this, dateListener,yr, mon, dy).show();
}
});
timeButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new TimePickerDialog(MainActivity.this, timeListener,h,m,true).show();
}
});
}
Page 17
Mobile Application Development Unit-IV
Android Fragments
Android Fragment is the part of activity, it is also known as sub-activity. There can be more than one
fragment in an activity. Fragments represent multiple screen inside one activity.
Android fragment lifecycle is affected by activity lifecycle because fragments are included in activity.
Each fragment has its own life cycle methods that is affected by activity life cycle because fragments are
embedded in activity.
The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.
Page 18
Mobile Application Development Unit-IV
Page 19
Mobile Application Development Unit-IV
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello_blank_fragment"/>
</FrameLayout>
File: fragment_fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:background="#F0FFFF"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello_blank_fragment"/>
</FrameLayout>
MainActivity class
File: MainActivity.java
packagein.kvsw.fragments;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
File: Fragments1.java
package in.kvsw.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
Page 21
Mobile Application Development Unit-IV
@Override
public View onCreateView(LayoutInflaterinflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
File: Fragment2.java
package in.kvsw.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflaterinflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}
Output:
Page 22