DOC-20240515-WA0006.
DOC-20240515-WA0006.
2. Explain the concept of Understanding the Life Cycle of an Activity. Example. [IT-REG-
2019] [IT-SUP-2021] [BCA-SUP-2021] [IT-REG-2022]
The Activity base class defines a series of events that governs the life cycle of an activity.
The Activity class defines the following events:
onCreate() — Called when the activity is first created
1
onStart() — Called when the activity becomes visible to the user
onResume() — Called when the activity starts interacting with the user
onPause() — Called when the current activity is being paused and the previous activity is
being resumed
onStop() — Called when the activity is no longer visible to the user
onDestroy() — Called before the activity is destroyed by the system (either manually or
by the system to conserve memory)
onRestart() — Called when the activity has been stopped and is restarting again
Understanding
By default, the activity created for you contains the onCreate() event.
Within this event handler is the code that helps to display the UI elements of your screen.
The life cycle of an activity and the various stages it goes through from when the activity is
started until it ends.
MainActivity.java
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
2
import android.util.Log;
public class MainActivity extends Activity
{
String tag = “Events”;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, “In the onCreate() event”);
}
public void onStart() {
super.onStart();
Log.d(tag, “In the onStart() event”);
}
public void onRestart(){
super.onRestart();
Log.d(tag, “In the onRestart() event”);
}
public void onResume() {
super.onResume();
Log.d(tag, “In the onResume() event”);
}
public void onPause(){
super.onPause();
Log.d(tag, “In the onPause() event”);
}
public void onStop() {
super.onStop();
Log.d(tag, “In the onStop() event”);
}
public void onDestroy(){
super.onDestroy();
Log.d(tag, “In the onDestroy() event”);
}
}
The execution of lifecycle of an activity is as follows:
When the activity is first loaded
In the onCreate() event
In the onStart() event
In the onResume() event
Press the back button of an Activity
In the onPause()event
In the onStop()event
In the onDestroy()event
Click the Home button and hold it
In the onCreate()event
In the onStart()event
3
In the onResume()event
Press the Phone button on the Android Emulator so that the activity is pushed to the
background.
In the onPause()event
In the onStop()event
The onDestroy() event is not called, indicating that the activity is still in memory. Exit
the phone dialer by pressing the Back button. The activity is now visible again.
In the onRestart()event
In the onStart()event
In the onResume()event
The onRestart() event is now fired, followed by the onStart() and onResume() events.
4
import android.view.Window;
public class MainActivity extends Activity {
String tag = “Events”;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
}
}
b. Confirmation Dialogs
Confirmation dialogs require users to explicitly confirm their choice before an option
is committed. For example, users can listen to multiple ringtones but only make a
final selection upon touching “OK”
i. Single choice: In this only one item can be selected
ii. Multiple choice: This dialog is used when we want to select more than one item in
a
dialog.
iii. Time picker: This dialog picker is used to select a single date.
iv. Date picker: The time picker dialog allows the user to pick a time, and adjusts to
the
user’s preferred time setting, i.e. the 12-hour or 24-hour format
iv.TimePicker
c. Bottom Sheet Dialog
Bottom sheets slide up from the bottom of the screen to reveal more content.
5
Bottom sheet dialog full screen dialog
d. Full screen dialog
Full-screen dialogs group a series of tasks (such as creating a calendar entry) before they may
be committed or discarded. No selections are saved until “Save” is touched. Touching the
“X” discards all changes and exits the dialog.
Ex 1: MainActivity.xml
<?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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="close app" />
</LinearLayout>
6
MainActivity.java
package com.example.ex1;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends
AppCompatActivity {
Button closeButton;
AlertDialog.Builder builder;
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
closeButton = (Button)
findViewById(R.id.button);
builder = new AlertDialog.Builder(this);
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
builder.setMessage("Do you want to close the application");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
Toast.makeText(getApplicationContext(), "",Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(getApplicationContext(),"you choose the no action in the
alert box",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert =builder.create();
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}
7
Ex 2: MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
boolean[] itemsChecked = new boolean [items.length];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(0);
}
});
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(“This is a dialog with some simple text...”)
.setPositiveButton(“OK”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
Toast.makeText(getBaseContext(), “OK clicked!”, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(“Cancel”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),“Cancel clicked!”, Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(), items[which] + (isChecked ? “ checked!”: “unchecked!”),
Toast.LENGTH_SHORT).show();
}
})
8
.create();
}
return null;
}
}
The code contains two buttons: OK and Cancel, using the setPositiveButton() and
setNegativeButton() methods, respectively. The user also set a list of checkboxes for users to
choose via the setMultiChoiceItems() method. For the setMultiChoiceItems() method, you
passed in two arrays: one for the list of items to display and another to contain the value of
each item to indicate if they are checked. When each item is checked, the Toast class to
display a message.
9
_progressHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (_progress >= 100) {
_progressDialog.dismiss();
} else {
_progress++;
_progressDialog.incrementProgressBy(1);
_progressHandler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
_progressDialog = new ProgressDialog(this);
_progressDialog.setIcon(R.drawable.icon);
_progressDialog.setTitle(“Downloading files...”);
_progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
_progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, “Hide”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(), “Hide clicked!”, Toast.LENGTH_SHORT).show();
}
});
_progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, “Cancel”, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(), “Cancel clicked!”, Toast.LENGTH_SHORT).show();
}
});
return _progressDialog;
}
return null;
}
}
10
An Android application can contain zero or more activities. When your application has
more than one activity, you may need to navigate from one activity to another. To
navigate between activities is done by using an intent.
Intents: Android Intent is the message that is passed between components such as
activities, content providers, broadcast receivers, services etc.The “glue “ that
connects different activities
Intents are two types:
a. Implicit Intents
Implicit intent doesn’t specify the component.
Intent provides the information of available components provided by the system
that is to invoked.
To navigate between activities present in different application
Ex: By clicking the you tube link available in what’s app status, navigating to you
tube application
Syntax:
Intent i=new intent(Intent.ACTION_VIEW);
i.setData(Uri.Parse(“htttp://www.vignan.ac.in”);
startActivity(i);
or
Intent i=new intent(Intent.ACTION_VIEW, Uri.Parse(“htttp://www.vignan.ac.in”);
startActivity(i);
Implicit Intents examples please Refer the concept of Calling Built in Apps Using Intents.
b. Explicit Intents
Explicit Intents specifies the component.
Intent provides the external class to be invoked.
To navigate between activities present in same application
Ex: In what’s app Navigating between status, calls, and chats.
Syntax:
Intent i=new intent(this,SecondActivity.class);
startActivity(i);
The following is the example of Explicit Intents:
AndroidManifest.xml
<?xmlversion=”1.0”encoding=”utf-8”?>
<manifestxmlns:android=”http://schemas.android.com/apk/res/android”
package=”net.learn2develop.Activities”
android:versionCode=”1”
android:versionName=”1.0”>
<application android:icon=”@drawable/icon”android:label=”@string/app_name”>
<activity android:name=”.MainActivity”
android:label=”@string/app_name”
android:theme=”@android:style/Theme.Dialog” >
<intent-filter>
<actionandroid:name=”android.intent.action.MAIN” />
<categoryandroid:name=”android.intent.category.LAUNCHER” />
</intent-filter>
11
</activity>
<activity android:name=”.Activity2”
android:label=”Activity 2”>
<intent-filter>
<action android:name=”net.learn2develop.ACTIVITY2” />
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
</application>
Activity2.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is Activity 2!”
/>
</LinearLayout>
Activity2.java
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
public class Activity2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
} }
MainActivity.java
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.KeyEvent;
import android.content.Intent;
public class MainActivity extends Activity {
String tag = “Events”;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
12
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
}
return false;
}
}
9. Explain about Returning Results from an Intent OR Give the steps to get a result from
an activity? Example [MCA-REG-2022]
The startActivity() method invokes another activity but does not return a result to the
current activity. For example, you may have an activity that prompts the user for user
name and password.
The information entered by the user in that activity needs to be passed back to the
calling activity for further processing. If you need to pass data back from an activity,
you should instead use the startActivityForResult() method.
Mainactivity.xml file
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<Button
android:id=”@+id/btn_OK”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
14
android:text=”Display Second Activity”
android:onClick=”onClick”/>
</LinearLayout>
secondactivity.xml file
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is the Second Activity!” />
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Please enter your name” />
<EditText
android:id=”@+id/txt_username”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<Button
android:id=”@+id/btn_OK”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”OK”
android:onClick=”onClick”/>
</LinearLayout>
SecondActivity.java:
package net.learn2develop.UsingIntent;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class SecondActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void onClick(View view) {
Intent data = new Intent();
EditText txt_username = (EditText) findViewById(R.id.txt_username);
data.setData(Uri.parse(txt_username.getText().toString()));
15
setResult(RESULT_OK, data);
finish();
}
}
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class UsingIntentActivity extends Activity {
int request_Code = 1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
startActivityForResult(new Intent(“net.learn2develop.SecondActivity”),request_Code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
}
}
When the first activity is loaded, click the button. SecondActivity will now be loaded.
Enter your name and click the OK button. The first activity will display the name you
have entered using the Toast class.
In order for an activity to return a value to the calling activity, you use an Intent object to
send data back via the setData() method:
The setResult() method sets a result code (either RESULT_OK or
RESULT_CANCELLED) and the data (an Intent object) to be returned back to the
calling activity.
The finish() method closes the activity and returns control back to the calling activity.
The onActivityResult() method, which is called whenever an activity returns.
It checks for the appropriate request and result codes and display the result that is
returned.
The returned result is passed in via the data argument; and finally obtain its details
through the getData() method.
16
Three different ways to pass the data using an Intent Object
a. putExtra() method
b. putExtras() method
c. setData() method
a. putExtra() method:
Use the putExtra() method of an Intent object to add a name/value pair
o i.putExtra(“str1”, “This is a string”);
o i.putExtra(“age1”, 25);
The preceding statements add two name/value pairs to the Intent object: one of type
string and one of type integer.
To obtain the data sent using the Intent object use the getIntent() method. Then, call its
getStringExtra() method to get the string value set using the putExtra() method:
Toast.makeText(this,getIntent().getStringExtra(“str1”),Toast.LENGTH_SHORT).show();
For the integer value, use the getIntExtra() method (the second argument is the default
value in case no value is stored in the specifi ed name):
Toast.makeText(this,Integer.toString(getIntent().getIntExtra(“age1”,0)),
Toast.LENGTH_SHORT).show();
b. putExtras() method:
Bundle object as a dictionary object — it contains a set of name/ value pairs
o Bundle extras = new Bundle();
o extras.putString(“str2”, “This is another string”);
o extras.putInt(“age2”, 35);
o i.putExtras(extras);
To retrieve the Bundle object, use the getExtras() method:
Bundle bundle = getIntent().getExtras();
Toast.makeText(this, bundle.getString(“str2”),Toast.LENGTH_SHORT).show();
Toast.makeText(this,Integer.toString(bundle.getInt(“age2”)),Toast.LENGTH_SHO
RT).show();
c. setData() method:
Use the setData() method to return some value.
i.setData(Uri.parse( “Something passed back to main activity”));
To retrieve the data set using the setData() method, use the getData() method.
Toast.makeText(this, data.getData().toString(),Toast.LENGTH_SHORT).show();
Ex: Besides returning data from an activity, it is also common to pass data to an activity. For
example, to set some default text in the EditText view before the activity is displayed. Use
the Intent object to pass the data to the target activity.
main.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<Button
17
android:id=”@+id/btn_SecondActivity”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Click to go to Second Activity”
android:onClick=”onClick”/>
</LinearLayout>
secondactivity.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Welcome to Second Activity” />
<Button
android:id=”@+id/btn_MainActivity”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Click to return to main activity”
android:onClick=”onClick”/>
</LinearLayout>
SecondActivity.java
package net.learn2develop.PassingData;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SecondActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
Toast.makeText(this,getIntent().getStringExtra(“str1”), Toast.LENGTH_SHORT).show() ;
Toast.makeText(this,Integer.toString(getIntent().getIntExtra (“age1”,0)),Toast.LENGTH_SHORT).show();
Bundle b = getIntent().getExtras();
Toast.makeText(this, b.getString(“str2”),Toast.LENGTH_SHORT).show();
Toast.makeText(this,Integer.toString(bundle.getInt(“age2”)),Toast.LENGTH_SHORT).show();
}
public void onClick(View view) {
Intent i = new Intent();
i.putExtra(“age3”, 45);
i.setData(Uri.parse(“Something passed back to main activity”));
18
setResult(RESULT_OK, i);
finish();
}
}
MainActivity.java
package net.learn2develop.PassingData;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class PassingDataActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
Intent i = new Intent(“net.learn2develop.PassingDataSecondActivity”);
i.putExtra(“str1”, “This is a string”);
i.putExtra(“age1”, 25);
Bundle extras = new Bundle();
extras.putString(“str2”, “This is another string”);
extras.putInt(“age2”, 35);
i.putExtras(extras);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, Integer.toString(data.getIntExtra(“age3”, 0)),Toast.LENGTH_SHORT).show();
Toast.makeText(this, data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
}
}
19
Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.
The FragmentManager class is responsible to make interaction between fragment
objects.
Advantage of fragments:
we can only show a single Activity on the screen at one given point of time so we were
not able to divide the screen and control different parts separately. With the help of
Fragment’s we can divide the screens in different parts and controls different parts
separately.
By using Fragments we can comprise multiple Fragments in a single Activity. Fragments
have their own events, layouts and complete life cycle. It provide flexibility and also
removed the limitation of single Activity on the screen at a time.
Fragments were added in Honeycomb version of Android i.e API version 11. There are some
primary classes related to Fragment’s are:
1. FragmentActivity: The base class for all activities using compatibility based Fragment (and
loader) features.
2. Fragment: The base class for all Fragment definitions
3. FragmentManager: The class for interacting with Fragment objects inside an activity
4. FragmentTransaction: The class for performing an atomic set of Fragment operations such as
Replace or Add a Fragment.
There are two ways to add a fragment to an activity:
a) Statically (XML)
b) Dynamically ( Java)
20
android:name=”net.learn2develop.Fragments.Fragment1”
android:id=”@+id/fragment1”
android:layout_weight=”1”
android:layout_width=”0px”
android:layout_height=”match_parent” />
<fragment
android:name=”net.learn2develop.Fragments.Fragment2”
android:id=”@+id/fragment2”
android:layout_weight=”1”
android:layout_width=”0px”
android:layout_height=”match_parent” />
</LinearLayout>
Fragment1.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:background=”#00FF00” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is fragment #1”
android:textColor=”#000000”
android:textSize=”25sp” />
</LinearLayout>
Fragment2.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:background=”#FFFE00”>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is fragment #2”
android:textColor=”#000000”
android:textSize=”25sp” />
</LinearLayout>
Fragment1.java
package net.learn2develop.Fragments;
import android.app.Fragment;
21
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
}
Fragment2.java
package net.learn2develop.Fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
22
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”welcome”/>
</LinearLayout>
Mainactivity.java
package net.learn2develop.Fragments;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
public class FragmentsActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft =fm.beginTransaction();
WindowManager wm = getWindowManager();
Display d = wm.getDefaultDisplay();
if (d.getWidth() > d.getHeight())
{
Fragment1 f1 = new Fragment1();
fragmentTransaction.replace(android.R.id.content, f1);
}
else
{
Fragment2 f2 = new Fragment2();
fragmentTransaction.replace(android.R.id.content, f2);
}
ft.commit();
}
23
}
24
15. Create an application which implement the Life Cycle Methods of an Fragment.
package net.learn2develop.Fragments;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle
savedInstanceState) {
Log.d(“Fragment 1”, “onCreateView”);
return inflater.inflate(R.layout.fragment1, container, false);
}
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(“Fragment 1”, “onAttach”);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(“Fragment 1”, “onCreate”);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(“Fragment 1”, “onActivityCreated”);
}
public void onStart() {
super.onStart();
25
Log.d(“Fragment 1”, “onStart”);
}
public void onResume() {
super.onResume();
Log.d(“Fragment 1”, “onResume”);
}
public void onPause() {
super.onPause();
Log.d(“Fragment 1”, “onPause”);
}
public void onStop() {
super.onStop();
Log.d(“Fragment 1”, “onStop”);
}
public void onDestroyView() {
super.onDestroyView();
Log.d(“Fragment 1”, “onDestroyView”);
}
public void onDestroy() {
super.onDestroy();
Log.d(“Fragment 1”, “onDestroy”);
}
public void onDetach() {
super.onDetach();
Log.d(“Fragment 1”, “onDetach”);
}
}
Like activities, fragments in Android also have their own life cycle. As you have seen, when a
fragment is being created, it goes through the following states:
➤ onAttach()
➤ onCreate()
➤ onCreateView()
➤ onActivityCreated()
When the fragment becomes visible, it goes through these states:
➤ onStart()
➤ onResume()
When the fragment goes into the background mode, it goes through these states:
➤ onPause()
➤ onStop()
When the fragment is destroyed (when the activity it is currently hosted in is destroyed), it goes
through the following states:
➤ onPause()
➤ onStop()
➤ onDestroyView()
➤ onDestroy()
➤ onDetach()
26
Like activities, you can restore an instance of a fragment using a Bundle object, in the following
states:
➤ onCreate()
➤ onCreateView()
➤ onActivityCreated()
Fragments2.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:background=”#FFFE00” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is fragment #2”
android:textColor=”#000000”
27
android:textSize=”25sp” />
<Button
android:id=”@+id/btnGetText”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Get text in Fragment #1”
android:textColor=”#000000”
android:onClick=”onClick” />
</LinearLayout>
Main.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”horizontal” >
<fragment
android:name=”net.learn2develop.Fragments.Fragment1”
android:id=”@+id/fragment1”
android:layout_weight=”1”
android:layout_width=”0px”
android:layout_height=”match_parent” />
<fragment
android:name=”net.learn2develop.Fragments.Fragment2”
android:id=”@+id/fragment2”
android:layout_weight=”1”
android:layout_width=”0px”
android:layout_height=”match_parent” />
</LinearLayout>
Mainactivity.java
public class FragmentsActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Fragment2.java
package net.learn2develop.Fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
28
import android.widget.TextView;
import android.widget.Toast;
public class Fragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
public void onStart() {
super.onStart();
Button btnGetText = (Button) getActivity().findViewById(R.id.btnGetText);
btnGetText.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView lb = (TextView)getActivity().findViewById(R.id.lblFragment1);
Toast.makeText(getActivity(),lb.getText(),Toast.LENGTH_SHORT).show();
}
});
}
}
17. Explain about Calling built in apps using intents OR Example of Implicit Intents OR
Demonstrate about calling built-in apps using Intents [BCA-REG-2021]
One of the advantage of Android Programming is using the intents to call activities from other
applications.
Ex: Application needs to load a web page, so use the Intent object to invoke the built-in web
browser to display the webpage, instead of building your own web browser.
Main.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<Button
android:id=”@+id/btn_webbrowser”
android:layout_width=”fill_parent”
29
android:layout_height=”wrap_content”
android:text=”Web Browser”
android:onClick=”onClickWebBrowser” />
<Button
android:id=”@+id/btn_makecalls”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Make Calls”
android:onClick=”onClickMakeCalls” />
<Button
android:id=”@+id/btn_showMap”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Show Map”
android:onClick=”onClickShowMap” />
</LinearLayout>
MainActivity.java
package net.learn2develop.Intents;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class IntentsActivity extends Activity {
int request_Code = 1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickWebBrowser(View view) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(“http://www.amazon.com”));
startActivity(i);
}
public void onClickMakeCalls(View view) {
Uri u=Uri.parse("tel:9988776655");
Intent i=new Intent(Intent.ACTION_DIAL, u);
startActivity(i);
}
public void onClickShowMap(View view) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(“geo:37.827500,-122.481670”));
startActivity(i);
}
}
30
Intents usually come in pairs: action
and data.
The action describes what is to be
performed, such as editing an item,
viewing the content of an item, and
so on.
The data specifies what is affected,
as a person in the Contacts database.
The data is specified as an Uri
object.
The actions are ACTION_VIEW,
ACTION_DIAL, and
ACTION_PICK.
iv. Pass the data to the Intent object using setData() method:
Intent i=new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse(“http://www.vignan.ac.in”));
startActivity(i);
31
19. What do you understand about Intent Filters.
An Activity can invoke another activity using the Intent object.
To invoke activity, another way is to specify the action and category within the
<intent- filter> element in AndroidManifest.xml file.
<intent-filter>
<action android:name = ”net.learn2develop.SecondActivity”/>
<category android:name = “android.intent.category.DEFAULT”/>
</intent-filter>
The intent filter name for the new activity is net.learn2develop.SecondActivity. Other
activities that wish to call this activity will invoke it via this name. Ideally, you should
use the reverse domain name of your company as the intent filter name in order to reduce
the chances of another application having the same intent filter name.
The category for the intent filter is android.intent.category.DEFAULT. To add this to the
intent filer so that this activity can be started by another activity using the startActivity()
method.
22. What is an Activity which methods implemented by all sub classes of an Activity?[IT-
REG-2022]
An Activity is the screen representation of an application in Android.
It serves as an entry point for the user’s interaction. Each activity has a layout file where you can
place your UI. An application can have different activities. For example, facebook start page
where you enter your email/phone and password to login acts as an activity.
32
Below are the two methods which almost all subclasses of Activity will implement:
onCreate(Bundle): It is a method where your initialization is done. Under this, you will
callsetContentView(int) with a layout resource which defines your UI. Also, you can
retrieve the widgets in that UI by using findViewById(Int). These are required to interact
programmatically.
onPause(): It is a method which deals with the user whenever it leaves the activity. So
any changes made by the user should be commited which is done by
the ContentProvider that holds the data.
33