0% found this document useful (0 votes)
16 views39 pages

Activity Overview & Intents

Uploaded by

rhenzviloria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views39 pages

Activity Overview & Intents

Uploaded by

rhenzviloria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Activity Overview

MOBDEVE – AY2324T1 – ETighe


Outline
• Motivation
• Defining an Activity
• Defining Context
• Handling Multiple Activities
• Passing Data Between Activities
Open your Contacts App

What functionalities
can you identify?
Don’t worry about formalities,
just try to identify what
functions you think it has J
(Some) Contacts Functionality

• List of Contacts • Search


• Add Contact • Settings
• View Contact • Export / Share Contact
• Edit contact • Manage Account
• Delete Contact • Block Numbers
• Call Contact
Reflect: How did you identify
functions?
Streamlining Contacts Functionality…

• View All Contacts (Home) • Manage Settings


• View favorites • Manage Account
• Search
• View Block Numbers
• Share contact
• Add+Edit Contact
• View Contact Details
• Delete contact
• Share/export contact
Block Numbers Most functionalities are contained in their own View Contact Screen
screen. If a screen has more than one functionality,
its because the functions complement each other,
like how searching makes viewing easier.

Main Screen
Manage Accounts

Add/Edit Contact Screen


Settings

Some screens are reusable (e.g. Add/Edit), while


other screens are of different apps (e.g. Manage
Accounts).
What is an Activity?
What is an Activity?
• Basic component of an Android
Application
• Provides a framework for the code to
interact with the layouts
• Usually associated to a layout file,
which it handles inflating
What is an Activity?
• Usually thought of as a single screen
• Single screen == Single task
• Or at least a set of related tasks…
• Hence, a major task of an app can be
the basis for an activity
• Functions very much like a Controller
• C in MVC
• In charge of handling events and
displaying/passing data
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ph.edu.dlsu.ccs.a04_multiple_activities">

<application
Notice…
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" • There is no main
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" function for Android
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
apps
<intent-filter>
<action android:name="android.intent.action.MAIN" /> • The Android system
<category android:name="android.intent.category.LAUNCHER" /> lunches a main
</intent-filter>
</activity>
activity as defined in
<activity android:name=".Choice01Activity" />
<activity android:name=".Choice02Activity" />
the Manifest
<activity android:name=".FinalActivity"></activity> Main -> Define an activity as an entry point to the app
</application> Launcher -> Indicates an activity as part of the
system’s app launcher
</manifest>
Creating an Activity
Activity
• When creating an activity by default…
By default, I mean by allowing Android Studio to do so…

This way, Android Studio automatically adds a layout file and an Activity details needed in the Manifest.
You can create an Activity from scratch, but make sure to create a layout file and define the activity in the
Manifest or else Android won’t recognize it.
Activity
• When creating an activity by default, notice that an
activity is a class that extends AppCompatActivity
• AppCompatActivity is a subclass of Activity
• Compat -> Compatible – implying this will work on older
devices
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Activity
• Additionally, by default, Activities are associated to a
Layout (and it resources) through setContentView()
• Can only have one ContentView at a time
• Typically, you’d have one activity associated to one layout
• Multiple activities could use the same layout [if reusable]
Just like what we did
public class MainActivity extends AppCompatActivity {
with a ViewHolder’s @Override If the ContentView
View in the protected void onCreate(Bundle savedInstanceState) { isn’t properly set up,
RecyclerView, super.onCreate(savedInstanceState); your Activity won’t be
setOnContactView() setContentView(R.layout.activity_main); able to access the
inflates the provided } the layout properly
layout
Activity à Context
• If you traces the superclass of Activity, you’ll find that
an Activity is also Context
• Context is an interface to global information about an
application | activity (i.e. it’s environment)
• It allows access to
resources and
classes
public class MainActivity extends AppCompatActivity { RECALL
private EditText first_name_et; When creating Views, we need to pass it a
private EditText last_name_et; Context object.
private Button add_btn;
private LinearLayout name_list_vll;
There are a few ways to reference a
@Override Context object:
protected void onCreate(Bundle savedInstanceState) { • Activity.this (the activity’s context)
super.onCreate(savedInstanceState); • View.getContext() [the View’s associated
setContentView(R.layout.activity_main); context, whatever that may be]
• getApplicationContext() [the context of
this.first_name_et = findViewById(R.id.firstname_etv); the entire application, not just the
this.last_name_et = findViewById(R.id.lastname_etv);
activity]
this.add_btn = findViewById(R.id.add_btn);
this.name_list_vll = findViewById(R.id.namelist_vll);
In this case, its actually better to use
this.add_btn.setOnClickListener(new View.OnClickListener() { MainActivity.this or view.getContext() –
@Override not getApplicationContext().
public void onClick(View view) {
TextView temp_tv = new TextView(MainActivity.this);
temp_tv.setText(last_name_et.getText() + ", " + first_name_et.getText()); Rule of thumb is that if the object that
name_list_vll.addView(temp_tv); required context is centered on the
} activity (like Views), use the Activity’s
}); context. Otherwise, use the
} Application’s context. J
}
Questions so far?
Multiple Activities
• Simple applications might
only need one activity, but
this is rarely the case
• Most apps have multiple
activities with each
corresponding to a specific
functionality
This implies that we’d need to to link
our Activities together somehow…
Moving from Activity to Activity
• In order to move to another Activity, we don’t instantiate
the second activity
• Instead, we send a “message” to the system and
request for the other activity to be launched
• For this, we’ll need to create + instantiate an Intent object
and request for that an activity be started, as such:
Intent intent = new Intent(SourceActivity.this, DestinationActivity.class);
startActivity(intent);

Context
Moving from Activity to Activity
• Once in the new activity, you can return to the previous
activity by clicking the back button
Design Tip:
Avoid creating a back
button if all it does is
redirect to the previous
screen. If its logic
mimics the system’s
back button, there’s no
need to include it.
Moving from Activity to Activity
• When using startActivity(), your app creates the
destination Activity and moves that to the front of the
Activity stack
In the visualization to the side, we see that the active
Activity (on top of the stack) is the View Contact screen.
This is where the user currently is.

If we click the system’s back button from this screen, the


Android system would “destroy” the current activity and
return focus to the previous activity still in the stack.
Moving from Activity to Activity
• Don’t abuse startActivity()!
• It is possible to cycle between Activities that don’t really
need to return to each other’s previous states
For demonstration's sake, the Activity stack presented to
the side is a result of having two activities constantly use
startActivity

Imagine being the user and pressing the back button – you’ll
basically be cycling through all the previously started
activities… and that would be pretty annoying.
Moving from Activity to Activity
• Don’t abuse startActivity()!
• As a solution: use finish() directly after starting an activity
• finish() signals to the OS that the current activity is to be
destroyed
Activity Stack

startActivity(i);
finish();
Let’s look at another example…
Activity Stack

startActivity(i);

Uses the system’s startActivity(i);


Basically, clicking the
back button finish();
system’s back button is very
much like the finish() method
Moving from Activity to Activity
• Bottomline, be mindful of how you start and finish your
activities
• You might run into issues where the user would access data
that’s already supposed to be committed… which can
possibly lead to more issues
New Scenario…
• From the Home Screen of our
Contacts App example, let’s say
we click on Contact #2…
• Our app should open the View
Contact Screen with Contact #2’s
data
• Question: How do we get Contact
#2’s data from the Home Screen to
the View Contact Screen?
Intents
Data of
selected
contact
• Aside from communicating to
the OS, Intents are also used
to communicate between apps
• As Intents are like messages, Data of newly
created contact
we can store data inside of
them an open them up in the
destination
• For this, we can use Extras!
Intents and Extras
• To place data inside intents,
utilize intent.putExtra()
• This needs a String tag and a value
• To retrieve data, utilize
intent.get<type of data>Extra()
• Refer to the API for the methods
• Some methods require a default
value
We also use getIntent() in the destination activity
Putting it All Together
In our example here, we want to send the integers 4 and 6 to the
AdditionActivity, where we’ll add both the numbers together…

Source Activity (MainActivity) Destination Activity (AdditionActivity)

public static String ADDEND_1_TAG = "ADDEND_1"; public static String ADDEND_1_TAG = "ADDEND_1";
public static String ADDEND_2_TAG = "ADDEND_2"; public static String ADDEND_2_TAG = "ADDEND_2";

… From: MainActivity …
To: AdditionActivity
Intent intent = new Intent( Intent intent = getIntent();
MainActivity.this, int addend1 = intent.getIntExtra(
AdditionActivity.class); MainActivity.ADDEND_1_TAG,
Intent.addExtra(ADDEND_1_TAG , 4) ADDEND_1; 4 0); // Second argument is for a default value
Intent.addExtra(ADDEND_2_TAG , 6) ADDEND_2; 6 int addend2 = intent.getIntExtra(
startActivity(intent); MainActivity.ADDEND_2_TAG,
0);
int result = addend1 + addend2
Expecting a Return Value(s)
• If we’re expecting the destination activity to return a
value to the source activity, we can make use of
ActivityResultLauncher
• Previously, the solution for this was to use
startActivityForResult(), but this has since been depreciated
Expecting a Return Value(s)
• To demonstrate
ActivityResultLauncher, let’s
consider the following application
with 2 activities
• First activity accepts 2 numbers and
sends them to the second activity for
adding
• Second activity adds both numbers
and sends the result back to the first
activity for it to be displayed
4

9
10
11 5

7
8

1
At this point, some of you might be
2 thinking this is a lot of effort to move
data around… and you’re right to think
3
so. However, given how Android treats
Activities, this is a way to transfer
data around
Questions?
Summary
• Activities are basic components of any Android
application
• Streamline functionalities of an application
• E.g. Home Page, Settings, View, Add/Edit, etc.
• Context allows access to resources and classes
• Is needed by certain objects, like Views
• Can be given at different levels: Activity, Application
Summary
• Its rare for an application to have only one Activity
• To move to another Activity, we need to create an intent
and use startActivity(i)
• We have to be mindful of how our Activities can stack and
should use finish() when needed
• We can also send data to other activities through
Extras
• If we’re expecting the destination to return a result, we
can use ActivityResultLauncher
For access to the project for the ActivityResultLauncher code, please see the Module in Canvas
Thanks everyone!

Image sauce: https://devrant.com/rants/1897105/making-a-meme-to-pass-the-time-all-this-waiting-only-because-i-wanted-to-try-one

You might also like