Chapter Four
INTENT
Intent
Apps can contain more than one Activity
For example, if your app is simple it can display a list of recipes.
But most of time, you will need to use multiple activities one for
displaying the list of recipes and another for adding a single recipe.
You start an activity by creating an intent and using it in the
startActivity() method.
Android Intent is the message that is passed between components
such as activities, content providers, broadcast receivers, services
etc. The dictionary meaning of intent is intention or purpose. So, it
can be described as the intention to do action.
A messaging app could start an activity in a camera app to take a
picture, then start an activity in an email app to let the user share the
picture in email.
Intent Applications
Generally using intents we can achieve:
Sending the User to Another App
Getting a Result from an Activity
Allowing Other Apps to Start Your Activity
Start
App Components (Activities, Services, send
broadcast ).
Types of Intent
Two types of intent
i) Implicit intent
ii) Explicit intent
Implicit intent: Implicit Intent doesn't specify the component(). In such
case, intent provides information of available components provided
by the system that is to be invoked.
When you use an implicit intent, Android uses the information in the
intent to figure out which components are able to receive it. So you
leave the details of which activity performs it to Android. Android
does this by checking the intent filters in every app’s copy of
AndroidManifest.xml.
Cont’d
Intent Filters: specify the kind of Intent your activity will accept.
Intent filters may contain the following three elements
<action>: The Intent action that the activity accepts
<data>: The type of data accepted by activity. The data can be represented by
MIME type or other attributes of the data URI.
<category>: the intent category
The main activity of your app needs an Intent filter that defines the “main”
action and the “launcher” category so the system can launch your app.
<intent-filters> This specifies that this is the
<action android:name=“android.intent.action.MAIN” /> app’s “main” entry point
<category
This activity should be listed
android:name=“android.intent.category.LAUNCHER” />
in the systems app launcher
Intent Action Types
Our Application can request different action depending on our
interest.
This are commonly used Action Types
Action Type Description
ACTION_CALL Brings up a phone dialer and immediately initiates a call
using the number supplied in the Intent’s data URI
ACTION_SEND Also known as the share intent, when you have some data
that the user can share through another app, such as an
email app or social sharing app.
ACTION_VIEW when you have some information that an activity can show
to the user. E.g webpages, photos
Intent Filter Example
E.g. Here’s the entry for an activity that can handle an action of ACTION_SEND.
The activity is able to accept data with MIME types of text/plain or image:
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
N.B If an Activity does not include Intent filters, it can only be launched with an
explicit intent
Any Activity that you want to accept an implicit intent must include the
android.intent.category.Default intent filter
Implicit Intent Example
The intent requests applications that can handle send action
having textual data.
Intent intent = new If you always want your user to choose an Activity
Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain"); intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, intent.putExtra(Intent.EXTRA_TEXT, "Hello");
"Hello"); String chooserTitle = getString(R.string.chooser);
startActivity(intent) Intent chosen= Intent.createChooser(intent,chooserTitle);
startActivity(chosen);
Explicit Intent
Explicit intent: Explicit Intent specifies the component. In such case,
intent provides the external class to be invoked in our app. We are
explicitly tell Android which class is expected to run.
Explicit Intent work internally within an application to perform navigation
and data transfer.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Create the second activity and
layout
In the app/src/main/java folder, choose
File → New → Activity, and choose the option for Empty Activity.
You will be presented with a new screen where you can choose
options for your new activity.
Check the activity in AndroidManifest.xml
Let say your First activity is sendMessageActivity and your second
activity is receiveMessageActivity
Send message Activity
public void onSendMessage(View view) {
EditText messageView = (EditText) Receive message Activity
findViewById(R.id.message); Intent intent = getIntent();
String messageText = String messageText =
messageView.getText().toString(); intent.getStringExtra(“message”);
Intent intent = new Intent(this, TextView messageView =
ReceiveMessageActivity.class); (TextView)findViewById(R.id.message);
intent.putExtra(“message”, messageText); messageView.setText(messageText);
startActivity(intent);
}
}
Getting data from Activity
The steps to get result from Activity
We use Start Activity for result with the Intent and a Request
code
Create a new Intent in the launched activity and add the
return data to that intent
Implement onActivityResult in the original activity to process
the returned data
In most cases this method takes two parameters; intent object and request
code. To pass the information to another activity and to uniquely identify our
request to that activity respectively.
The request code is an integer that identifies the request and can be used to
differentiate between results when you process the return data
For e.g. if you launch one activity to take a photo and another to pick a
photo from a gallery, we need different request codes to identify which
request the returned data belongs to.
Our Activity needs to override onActivityResult method that is invoked automatically when the
second activity returns result.
onActivityResult() method
The three arguments to onActivityResult() contain all the information you
need to handle the return data.
Request code: The request code you set when you launched
the Activity with startActivityForResult()
Result code: the result code set in the launched Activity, usually
one of RESULT_OK or RESULT_CANCELED
Intent data: The intent that contains the data returned from the
launched Activity.
In the next, we will see how we get results from an activity.
Get Activity class
final int REQUEST_Code = 2;
public void onClick(View view) {
Intent intent = new Intent(this, GiveActivity.class);
intent.putExtra(“message”, messageText);
startActivityForResult(intent,2);
}
Protected void onActivityResult(int requestCode, int resultCode,Intent
intent){
If (requestCode == REQUEST_Code && resultCode == RESULT_OK){
Textview.setText(intent.getStringExtra(“message”));
}
}
Give Activity class
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra(“message”, “Hi”);
setResult(RESULT_OK,intent);
finish();
}
List View and Adapter
A list view allows you to display a list of data that you can then use
to navigate through the app.
ListView is a ViewGroup that is used to display the list of scrollable of
items in multiple rows and the list items are automatically inserted to
the list using an adapter. Each view is positioned immediately below
the previous view in the list.
An adapter acts as a bridge between a view and a data source. It
reads data from various data sources, coverts it into View objects
and provide it to the linked Adapter view to create UI components..
Define ListView in XML
<LIstView
android:id=“@+id/”
android:layout_width=“”
android:layout_height=“”
android:divider=“@color/”
android:dividerHeight=“” />
android:divider: we can specify a divider between List items. A
drawable or any color can be specified as a value for this attribute.
android:dividerHeight: used to specify height of the divider
Organize our Activity
It is better to partition our ideas in to three different types of activity.
Top-level Activities
Category Activities
Detail/edit Activities
Top-level Activities: contains the things that are most important to
the user, and gives them an easy way of navigating to those things
In most apps, the first activity the user sees will be a top-level activity.
Category Activities: show the data that belongs to a particular
category, often in a list. This activities are often used to help the user
navigate to detail/edit activities.
Detail/edit Activity: displays details for a particular record, let the
user edit the record or allow the user to enter new records.
Types of Adapters
There are some commonly used Adapter in Android.
Base Adapter
Array Adapter
Custom Array Adapter
Simple Cursor Adapter
Base Adapter: is a base class of a general implementation of an Adapter
that can be used in ListView, GridView, Spinner etc.
we use when we need a customized list in a ListView or customized grids
in a GridView. Base Adapter can be extended to create a Custom
Adapter for displaying a custom list item.
public class CustomAdapter extends BaseAdapter {
@Override public int getCount() { return 0; }
@Override public Object getItem(int i) { return null; }
Override public View getView(int i, View view,
ViewGroup viewGroup) { return null; }
Cont’d
Array Adapter: is a type of adapter that specializes in working with
arrays.
Array Adapter is used when
Our data source is array e.g. list of phone contacts, countries
or name
By default, Array Adapter expects a Layout with a single TextView.
ArrayAdapter creates a view for each item by calling toString() on
each item and place the content in a TextView.
ArrayAdapter constructor takes the following parameters:
ArrayAdapter<String> adapter= new
ArrayAdapter<String>(this,android.R.layout.simple_list_item1,myStringArr
ay)
Cont’d(Array Adapter)
Context: the reference of current class
Resource: The layout that contains a TextView for each
string in the array.
Objects: The String Array.
Then we can simply call SetAdapter() on our ListView:
ListView listView= (ListView) findViewById(your listview id);
listView.SetAdapter(adapter);
Try to create list view that displays list of contacts name
String[] contactsname={};
Cont’d
N.B. For complex layouts or if there is need to customize our list view
or grid view Array Adapter is not suitable rather use custom
adapters.
Custom Array Adapters: ArrayAdapter is an implementation of
BaseAdapter, so if we want more customization then we can create
a custom adapter and extend ArrayAdapter on that class.
For e.g
if we want to create a view something other than a TextView like
displaying an image with text for each item, we extend the
ArrayAdapter class and override getView() to return the type of view
you want for each item.
Simple Cursor Adapter: An easy adapter to map columns from a cursor to
TextViews or ImageViews defined in an XML file. You can specify which columns
you want, which views you want to display the columns, and the XML file that
defines the appearance of these views.
Used when our data comes from database.
SimpleCursorAdapter Constructor takes the following parameters
SimpleCursorAdapter adapter = new SimpleCursorAdapter
(this,R.layout.simple_list_item_1,cursor,fromcolumns,toViews,0)
fromcolumns and toviews arrays tells which columns in the cursor to match to which
views
Try This …
Top Level Activity
xml <LinearLayout
android:orientation=“vertical”>
<ImageView
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@drawable/starbuzz_logo"
android:contentDescription="@string/starbuzz_logo" />
<ListView
android:id="@+id/list_options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/options" />
Strings.xml
<string-array name="options">
<item>Drinks</item>
<item>Food</item>
<item>Stores</item>
Cont’d
Java
//oncreatemethod
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> listView,
View itemView,
int position,
long id) {
if (position == 0) {
Intent intent = new Intent(TopLevelActivity.this,
DrinkCategoryActivity.class);
startActivity(intent);
}
}
};
//Add the listener to the list view
ListView listView = (ListView) findViewById(R.id.list_options);
listView.setOnItemClickListener(itemClickListener);
}
}
Drink Category Activity
Xml
<LinearLayout
android:orientation=“vertical”>
<ListView
android:id="@+id/list_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
To hold our drink data we will create pure java class
Refer the code Page no. 256 (The Drink class)
//oncreate method
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(
this,
Cont’d android.R.layout.simple_list_item_1,
Drink.drinks);
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
Java
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> listDrinks,
View itemView,
int position,
long id) {
//Pass the drink the user clicks on to DrinkActivity
Intent intent = new Intent(DrinkCategoryActivity.this,
DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id);
startActivity(intent);
}
};
//Assign the listener to the list view
listDrinks.setOnItemClickListener(itemClickListener);
Drink Detail Activity <LinearLayout
Xml android:orientation=“vertical”>
<ImageView
android:id="@+id/photo"
android:layout_width="190dp"
android:layout_height="190dp" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Cont’d public static final String EXTRA_DRINKID = "drinkId";
int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);
Java Drink drink = Drink.drinks[drinkId];
//Populate the drink name
TextView name = (TextView)findViewById(R.id.name);
name.setText(drink.getName());
//Populate the drink description
TextView description = (TextView)findViewById(R.id.description);
description.setText(drink.getDescription());
//Populate the drink image
ImageView photo = (ImageView)findViewById(R.id.photo);
photo.setImageResource(drink.getImageResourceId());
photo.setContentDescription(drink.getName());
Dialogs
Is small window that prompts the user to make a decision or
enter additional information's.
Dialog boxes in Android are partially transparent, floating
Activities or Fragments that partially obscure the user interface
A dialog doesn’t fill the screen and is normally used for modal
events that require users to take an action before they can
procced.
Why Dialogs
Dialogs can be used in different ways
Can be used to help users answers some questions
To make Selection
Display warning or error messages
Confirm Actions
Types of Dialog
The Dialog class is the base class for dialogs but we have to
instantiate the subclasses of Dialog rather than using directly.
In android the most commonly used types of dialogs are
Alert Dialog
Progress Dialog (Progress Bar)
Date and Time Picker
Custom Dialog
Alert Dialog: shows alert messages and gives the answer in the form
of yes or no. According to our response the next step is processed.
Cont’d[Alert Dialog]
Android Alert Dialog is built with three fields:
Title
Message(Content) Area
Action Button
Title: This is optional and should be used only when the content area is
occupied by a detailed message , a list or custom layout.
We use setTitle() method for displaying Alet Dialog box Title, setIcon() is used to
set the icon before the title.
Message(Content) Area: this can display a message, a list, or other custom
layout.
We use setMessage() method for displaying the message
Action Button: There should be no more than three action buttons in a
dialog.
Cont’d
Positive: used to accept and continue with the action(the “Ok” or
“Yes” action)
Negative: used to cancel the action(“No” action)
Neutral: used when the user may not want to proceed with the
action, but doesn't necessarily want to cancel (“Remind Me Later”
action)
We can add a list in Alert Dialog
A traditional single-choice list
A single-choice list (radio buttons)
A multiple-choice list (checkboxes
setItems() method can be used to add our list items.
setSingleChoiceItems() used to create a list of Radio Buttons
setMultipleChoiceItems() used to create a list of Check Boxes.
Example
Try to develop this dialog when a button is pressed.
Are you want to exit?
Yes No
Cont’d AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Alert")
.setMessage("Are you sure, you want to exit ?")
Java Code .setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
});
Progress Dialog: is used to display the status of work being done like
analyzing status of work or downloading a file.
By default the Progress Bar will be displayed as a Spinning wheel, if
we want to display it in a horizontal bar we have to change the style
property to horizontal like
style="?android:attr/progressBarStyleHorizontal".
Progress bar supports two type of modes to show the progress.
Determinate
Indeterminate
Determinate: progress mode is used in progress bar when we want
to show the quantity of progress has occurred. For example, the
percentage of file downloaded or percent remaining of an audio
file that is playing.
Cont’d
To use Determinate progress, we need to set the style of the progress bar
to progressBarStyleHorizontal and set the amount of progress
using android:progress attribute.
Indeterminate: progress mode is used in progress bar when we don’t know
how long an operation will take or how much work has done.
In indeterminate mode the actual progress will not be shown, only the cyclic
animation will be shown to indicate that some progress is happing.
Progress Bar is different from Progress Dialog
Progress
Bar is a View, which can be used in the layout to
show some progress while the user may still interact with other
parts
Progress Dialog is a Dialog with builtin Progress Bar
(depreciated in Api 26). It is used when we want to prevent
the user from interacting with the application. The Dialog
freezes the user from doing anything until it is dismissed
Indeterminate Mode
Using Progress Dialog
ProgressDialog loading;
loading= ProgressDialog(context,title,message,indeteminate(boolean), cancelable);
Using Progress Bar
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_centerHorizontal="true"/>
In our Activity
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// visible the progress bar
Determinate Mode
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMax(100); // Progress Dialog Max Value
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // Progress Dialog Style Horizontal
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog.getMax()) {
Thread.sleep(200);
progressDialog.incrementProgressBy(2);
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
Cont’d
Date and Timer Picker Dialog: A dialog that is used to select date
and time.
Custom Dialog: To create a Custom Dialog we need to create a
Custom Layout for the Dialog window with Layout and Widget
elements.
We set the custom layout as the dialog content view
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);