0% found this document useful (0 votes)
20 views65 pages

Week 5 Intent Activity and SharedPreferences

The document outlines the course content for CET3014N Mobile Application Development, focusing on Android application components such as Activities, Services, and Intents. It covers key topics like view binding, data storage options, JSON handling with Gson, and the use of RecyclerView for displaying lists. Additionally, it discusses explicit and implicit intents, permissions, and the structure of the AndroidManifest.xml file.

Uploaded by

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

Week 5 Intent Activity and SharedPreferences

The document outlines the course content for CET3014N Mobile Application Development, focusing on Android application components such as Activities, Services, and Intents. It covers key topics like view binding, data storage options, JSON handling with Gson, and the use of RecyclerView for displaying lists. Additionally, it discusses explicit and implicit intents, permissions, and the structure of the AndroidManifest.xml file.

Uploaded by

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

CET3014N Mobile Application Development

Lecturer : Dr. Noorul Hameed


Department of Computing, SoECBE
UOW Malaysia KDU Penang College
University
Course Contents

• Today’s lecture
• Activity
• Intents
• Starting activities
• Implicit Intents
• Returning results
• Native actions
• Data and File Storage overview
• JSON
• Adapters
• RecyclerView
• Spinner
• Dialog
• SharedPreferences
• Broadcast Receivers
WEEK: 5 Intent

 Application components are the essential building blocks of an


Android application.
 These components are loosely coupled by the application manifest
file AndroidManifest.xml that describes each component of the
application and how they interact.

• There are following four main components that can be used within an
Android application.
S. No. Components Description
1 Activities They dictate the UI and handle the user interaction to
the smart phone screen.
2 Services They handle background processing associated with
an application.
3 Broadcast They handle communication between Android OS and
Receivers applications.
4 Content Providers They handle data and database management issues.
Activities
WEEK: 5 What is an Activity?

 Android applications are created by bringing together one or more


components known as Activities.
 An activity is a single, standalone module of application
functionality that usually correlates directly to a single user
interface screen and its corresponding functionality.
 One activity cannot directly call methods or access instance data
of another activity. This, instead, is achieved using Intents and
Content Providers.
 API Reference:
super parent class

super parent class


WEEK: 5 Use view binding in Activity

 View binding
 View binding is a feature that makes it easier to write code
that interacts with views.

 Once view binding is enabled in a module, it generates a


binding class for each XML layout file present in that
module.

 An instance of a binding class contains direct references to


all views that have an ID in the corresponding layout.

 In most cases, view binding replaces findViewById.


android { ... buildFeatures { viewBinding = true } }

WEEK: 5 Use view binding in Activity (Cont.)

 Setup
 View binding is enabled on a module-by-module basis.
 To enable view binding in a module, set the viewBinding
build option to true in the module-level build.gradle.kts
file, as shown in the following example:
 android {
 ...
 buildFeatures {
 viewBinding = true
 }
 }
WEEK: 5 Use view binding in Activity (Cont.)

 View binding
example
 Sample Code in Kotlin:
private lateinit var binding: MainActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = MainActivityBinding.inflate(layoutInflater)
val view = binding.root
binding.name.text = “Hello World!”
binding.button.setOnClickListener { viewModel.userClicked() }
setContentView(view)

}
WEEK: 5 Use view binding in Activity (Cont.)

 Using Synthetic View Binding:


 Android Studio should prompt you to
 import kotlinx.android.synthetic.main.activity_main.* for
recyclerView.
 Sample Code in Kotlin:
 linearLayoutManager = LinearLayoutManager(this)
 recyclerView.layoutManager = linearLayoutManager
 This uses a synthetic reference to recyclerView without first
finding findViewById().
 As configured, the project uses the Kotlin Android Extensions
plugin that allows for importing views in a layout as synthetic
properties.
WEEK: 5 Intent

 An Intent is a messaging object you can use to


request an action from another app component.
There are three fundamental use cases:
 Starting an activity:
 Starting a service:
 Delivering a broadcast:
WEEK: 5 Intent (Cont.)

 Starting an activity:
 An Activity represents a single screen in an app. You
can start a new instance of an Activity by passing an
Intent to startActivity().
 The Intent describes the activity to start and carries any
necessary data.
 If you want to receive a result from the activity when it
finishes, call startActivityForResult(). Your activity
receives the result as a separate Intent object in your
activity's onActivityResult() callback.
WEEK: 5 Intent (Cont.)

 Starting a service: A Service is a component that performs


operations in the background without a user interface.
 You can start a service by using methods of the Service class.
 You can start a service to perform a one-time operation (such as
downloading a file) by passing an Intent to startService().
 The Intent describes the service to start and carries any
necessary data.
WEEK: 5 Intent (Cont.)

 Delivering a broadcast:
 A broadcast is a message that any app can receive.
 The system delivers various broadcasts for system events, such as
when the system boots up or the device starts charging.
 You can deliver a broadcast to other apps by passing an Intent to
sendBroadcast() or sendOrderedBroadcast().
WEEK: 5 Intent (Cont.)

 Types of Intents
 There are two types of intents as follows:
 Explicit intents
 Implicit Intents
WEEK: 5 Intent (Cont.)

 Explicit intents
 Explicit intents specify which component of which
application will satisfy the intent, by specifying a full
ComponentName.
 You'll typically use an explicit intent to start a component in
your own app, because you know the class name of the
activity or service you want to start.
 For example, you might start a new activity within your app
in response to a user action, or start a service to download
a file in the background.
WEEK: 5 Intent (Cont.)

 Implicit intents
 This do not name a specific component, but instead
declare a general action to perform, which allows a
component from another app to handle it.
 For example, if you want to show the user a location on a
map, you can use an implicit intent to request that another
capable app show a specified location on a map.
WEEK: 5 Intent (Cont.)

• Types of Intents (Cont.)


 Example For Explicit intents
// Executed in an Activity, so 'this' is the Context
var fileUrl: String="http://www.example.com/image.png"

val downloadIntent = Intent(this, DownloadService::class.java).apply {


data = Uri.parse(fileUrl)
}
startService(downloadIntent)

 The Intent(Context, Class) constructor supplies the app Context and the component a
Class object.
 As such, this intent explicitly starts the DownloadService class in the app.

• To start another activity (i.e. SecondActivity) explicitly:


val myActivity2 = Intent(this, SecondActivity::class.java)
startActivity(myActivity2)
WEEK: 5 Intent (Cont.)

• Types of Intents (Cont.)


 Example For Implicit intents
// Here is an example of how to use the Android intent resolver to send text:
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, textMessage)
type = "text/plain"
}
try {
startActivity(sendIntent)
} catch (e: ActivityNotFoundException) {
// Define what your app should do if no activity can handle the intent.
}
WEEK: 5 Intent (Cont.)

 Diagram for illustrating Intents operations

 Figure 1 shows how an intent is used when starting an activity.

Figure 1.

• How an implicit intent is delivered through the system to start another activity:
• [1] Activity A creates an Intent with an action description and passes it to startActivity().
• [2] The Android System searches all apps for an intent filter that matches the intent.
• When a match is found, [3] the system starts the matching activity (Activity B) by invoking its
onCreate() method and passing it the Intent.
WEEK: 5 Intent (Cont.)

 Returning Results

const val REQUEST_CODE: Int = 400


override fun onActivityResult(requestCode: Int, resultCode: Int, data:
Intent?) {

if (requestCode == Activity.RESULT_OK && requestCode ==


REQUEST_CODE) {
val message = data!!.getStringExtra("message")
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
WEEK: 5 Intent (Cont.)

 Returning Results

val intent = Intent().apply {


putExtra("message", "This is the quantity in amount")
}
setResult(Activity.RESULT_OK, intent)
finish()
WEEK: 5

Exercise 1:

Run Intent App


WEEK: 5

Data and File storage

overview
WEEK: 2 Data and file storage overview

Android file system provides several options for you to


save your app data:
App-specific storage: Store files that are meant for
your app's use only, either in dedicated directories
within an internal storage volume or different dedicated
directories within external storage.
WEEK: 5 File

Shared storage: Store files that your app intends to


share with other apps, including media, downloads,
documents, and other files.
Preferences: Store private, primitive data in key-
value pairs.
Databases: Store structured data in a private
database using the Room persistence library.
WEEK: 2 Application Manifest Using security model

uses-permission
• The uses-permission tags declare the permissions that
determined by your application needs for it to operate properly.
• The permissions you include will be presented to the user, to
grant or deny, during installation.
• Permissions are required for many of the native Android
services, particularly those with a cost or security implication
(such as dialing, receiving SMS, or using the location-based
services).
WEEK: 5 File Permissions

Accessing I/O requires permissions from Android runtime:


 <uses-permission
android:name="android.permission.INTERNET" />
 <uses-permission
android:name="android.permission.READ_EXTERNAL_STO
RAGE"/>
 <uses-permission
android:name="android.permission.WRITE_EXTERNAL_STO
RAGE"/>
WEEK: 2 Application Manifest Using security model

• ❑ uses-permission tag
• As shown in the item below, third-party applications, including
your own, can also specify permissions before providing
access to shared application components.

• Example (AndroidManifest.xml)
<uses-permission
android:name=”android.permission.ACCESS_LOCATION”>
</uses-permission>
WEEK: 5

JSON
WEEK: 5 JSON

JSON stands for Javescript Object Notatoion (JSON).


Gson
 is a popular Java library developed by Google for
serializing and deserializing Java/Kotlin objects to and from
JSON.
 Gson is widely used for handling JSON data exchanged
between the app and a server or stored locally.
WEEK: 5 JSON (Cont.)

To use Gson in an Android project, you typically include it as a


dependency in your build.gradle or build.gradle.kts file.
Here's how you can do it using Kotlin Domain Specific
Language (DSL):

Library module required:


dependencies {
implementation("com.google.code.gson:gson:2.8.8")
}
WEEK: 5 JSON (Cont.)

Sample Code:
import com.google.gson.Gson
// Define a data class representing your JSON data
data class Person(val name: String, val age: Int)
val json = "{\"name\":\"John\",\"age\":30}" // JSON string
// Deserialize JSON string to Kotlin object
val person: Person = Gson().fromJson(json, Person::class.java)
// Serialize Kotlin object to JSON string
val jsonString: String = Gson().toJson(person)
WEEK: 5 RecyclerView

RecyclerView is a part of the view group that contains a


single view that is recycled repeatedly to display the
corresponding data.
Suppoese we have item_layout as our single view which will
display our data repeatedly in a recycler format.
In addition layout, ArrayList will define all our data such as
images and text.
Then data can be displayed with the help of Adapter and
ViewHolder.
WEEK: 5 RecyclerView (Cont.)

 It still uses an Adapter to act as a data source; however, you


have to create ViewHolders to keep references in memory.

To provide a new view, RecyclerView either creates a new


ViewHolder object to inflate the layout and hold those
references, or it recycles one from the existing stack.
WEEK: 5 RecyclerView (Cont.)

 Components of a
RecyclerView
RecyclerView: The view on the screen where the list will be
displayed.

Item/data: The list of items that will be displayed.

Adapter: Maps the data to views.

ViewHolders - A pool of views for RecyclerView to use and


reuse to display. ViewHolders are created and reused in the
Adapter.
WEEK: 5 RecyclerView (Cont.)

 Implement your adapter and view holder

When you define your adapter, you override three key


methods:
onCreateViewHolder(): RecyclerView calls this method
whenever it needs to create a new ViewHolder. The method
creates and initializes the ViewHolder and its associated View,
but does not fill in the view's contents—the ViewHolder has not
yet been bound to specific data.
Sample Kotlin Code:
Refer to CustomAdapter.kt (in FruitsShop app)
WEEK: 5 RecyclerView (Cont.)

Implement your adapter and view holder

onBindViewHolder(): RecyclerView calls this method to associate a


ViewHolder with data.
The method fetches the appropriate data and uses the data to fill in the
view holder's layout.
For example, if the RecyclerView displays a list of names, the method
might find the appropriate name in the list and fill in the view holder's
TextView widget.
Sample Kotlin Code:
Refer to CustomAdapter.kt (in FruitsShop app)
WEEK: 5 RecyclerView (Cont.)

Implement your adapter and view holder

getItemCount(): RecyclerView calls this method to get the


size of the dataset.
For example, in an address book app, this might be the total
number of addresses.
RecyclerView uses this to determine when there are no more
items that can be displayed.
Sample Kotlin Code:
Refer to CustomAdapter.kt (in FruitsShop app)
WEEK: 5 RecyclerView (Cont.)

 RecyclerView using LayoutManager

 RecyclerView contains its own LayoutManager object.


 This object positions the RecyclerView’s items and tells it
when to recycle items that have transitioned off-screen.
 The RecyclerView has broken out this functionality to allow
for different kinds of layouts: Vertical, horizontal, grid,
staggered or custom.
WEEK: 5 RecyclerView (Cont.)

 RecyclerView using LayoutManager (Cont.)

Layout Managers offer three choices by default:


 LinearLayoutManager positions items to look like a
standard ListView.
 GridLayoutManager positions items in a grid format
similar to a GridView.
 StaggeredGridLayoutManager positions tems in a
staggered grid format.
WEEK: 5 Difference between RecyclerView and ListView

• Table 1: lists the differences between RecylerView and ListView.


WEEK: 5 Spinner

• Spinner View:
• Spinners provide a quick way to select one value from a set.
• In the default state, a spinner shows its currently selected value.
• Tapping the spinner displays a menu showing all other values the
user can select.
• Figure 1. A menu from a spinner, showing the available values.
WEEK: 5 Spinner (Cont.)

• Example in XML layout Using Spinner View:


• <Spinner
• android:id="@+id/planets_spinner"
• android:layout_width="match_parent"
• android:layout_height="wrap_content" />
WEEK: 5 Spinner (Cont.)

• Example in Kotlin Code:


val spnLocale: Spinner = findViewById(R.id.spnLocale)
spnLocale.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>,
view: View, i: Int, l: Long) {
// Your code here
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
// Do nothing
}
}
WEEK: 5

SharedPreferences
WEEK: 5 Preferences Using SharedPreferences class

• Definition:
• SharedPreferences is an interface used for accessing and
modifying preference data in Android.

• It handles objects that point to a file containing key-value


pairs and provides some methods to read and write them.

• You can use SharedPreferences to store primitive types


(Int, Float, Long, Boolean, String, and Set of Strings).
WEEK: 5 Preferences Using SharedPreferences class

• SharedPreferences.Editor: Interface used to write(edit)


data in the SP file. Once editing has been done, one must
commit() or apply() the changes made to the file.

• SharedPreferences.OnSharedPreferenceChangeListener(
): Called when a shared preference is changed, added, or
removed.

• This may be called even if a preference is set to its


existing value. This callback will be run on your main
thread.
WEEK: 5 Preferences Using SharedPreferences class

• There are five different methods are available in share


preference as shown below −
• Edit() − It going to edit shared preference values
• commit() − it going to commit shared preference values in
xml file.
• apply() − It going to commit back changes from editor to
shared preference.
• remove(String key) − It going to remove key and vales
from shared preference use key.
• Put() − It going to put key and values to shared preference
xml.
WEEK: 5 Preferences Using SharedPreferences class

• Following are the methods of Shared Preferences


• contains(String key): This method is used to check
whether the preferences contain a preference.
• edit(): This method is used to create a new Editor for
these preferences, through which you can make
modifications to the data in the preferences and atomically
commit those changes back to the SharedPreferences
object.
• getAll(): This method is used to retrieve all values from
the preferences.
WEEK: 5 Preferences Using SharedPreferences class

• getBoolean(String key, boolean defValue): This method


is used to retrieve a boolean value from the preferences.

• getFloat(String key, float defValue): This method is


used to retrieve a float value from the preferences.

• getInt(String key, int defValue): This method is used to


retrieve an int value from the preferences.
WEEK: 5 Preferences Using SharedPreferences class

• getLong(String key, long defValue): This method is


used to retrieve a long value from the preferences.

• getString(String key, String defValue): This method is


used to retrieve a String value from the preferences.

• getStringSet(String key, Set defValues): This method is


used to retrieve a set of String values from the
preferences.

WEEK: 5 Preferences Using SharedPreferences class

• registerOnSharedPreferencechangeListener(SharedPrefer
ences.OnSharedPreferencechangeListener listener):
• This method is used to register a callback to be invoked
when a change happens to a preference.

• unregisterOnSharedPreferencechangeListener(SharedPre
ferences.OnSharedPreferencechangeListener listener):
• This method is used to unregister a previous callback.
WEEK: 5 Preferences Using SharedPreferences class

• Kotlin Code:
import android.content.Context
import android.content.SharedPreferences
val sharedPreferences: SharedPreferences =
getSharedPreferences("MySharedPref",
Context.MODE_PRIVATE)
val myEdit: SharedPreferences.Editor =
sharedPreferences.edit()
myEdit.putString("name", name.text.toString())
myEdit.putInt("age", age.text.toString().toInt())
myEdit.apply()
WEEK: 5 Preferences Using SharedPreferences class

• Kotlin Code:
import android.content.Contextimport
android.content.SharedPreferences
val sh: SharedPreferences =
getSharedPreferences("MySharedPref",
Context.MODE_APPEND)
val s1: String = sh.getString("name", "") ?: "“
val a: Int = sh.getInt("age", 0)
name.text = s1age.text = a.toString()
The DialogFragment class also lets you reuse the dialog's UI as an embeddable component in a larger UI

WEEK: 5

Dialog
WEEK: 5 Dialog

 A dialog box that can show a title, up to three buttons, a list of


selectable items, or a custom layout.
 It is commonly used to display alerts, seek user confirmation, or
show information.
 There are two types of dialog:
 AlertDialog: Is simpler and quicker to implement for
straightforward dialogs
 DialogFragment: Is more complex but offers greater flexibility
and control
WEEK: 5 Dialog (Cont.)

 Kotlin Code:
val builder = AlertDialog.Builder(this)
builder.setTitle("Androidly Alert")
builder.setMessage("We have a message")
//builder.setPositiveButton("OK",
DialogInterface.OnClickListener(function = x))
builder.setPositiveButton(android.R.string.yes) { dialog, which ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
WEEK: 5 Dialog (Cont.)

builder.setNeutralButton("Maybe") { dialog, which ->


Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
builder.show()
WEEK: 5 Dialog (Cont.)

 DialogFragment:
 The DialogFragment class also lets you reuse the dialog's UI as
an embeddable component in a larger UI.
 Sample UI Layout/Design screen is shown in below:
The DialogFragment class also lets you reuse the dialog's UI as an embeddable component in a larger UI

WEEK: 5 Dialog (Cont.)

 Example for Kotlin Code Using DialogFragment


class StartGameDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
// Use the Builder class for convenient dialog construction.
val builder = AlertDialog.Builder(it)
builder.setMessage("Start game")
.setPositiveButton("Start") { dialog, id ->
// START THE GAME!
}
.setNegativeButton("Cancel") { dialog, id ->
// User cancelled the dialog.
}
// Create the AlertDialog object and return it.
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
The DialogFragment class also lets you reuse the dialog's UI as an embeddable component in a larger UI

WEEK: 5 Dialog (Cont.)

 Example for Kotlin Code Using DialogFragment

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_old_xml)
StartGameDialogFragment().show(supportFragmentManager,
"GAME_DIALOG")
}
}
The DialogFragment class also lets you reuse the dialog's UI as an embeddable component in a larger UI

WEEK: 5

BroadCastReceiver
WEEK: 5 Broadcast Receivers

• Android Broadcast Receivers are a component of the Android

application framework that allows your app to receive and respond

to broadcast messages from other applications or the system

itself.

• The system automatically sends broadcasts when various system

events occur, such as when the system switches in and out of

airplane mode.

• System broadcasts are sent to all apps that are subscribed to

receive the event.


Broadcast Receivers

https://www.youtube.com/watch?v=XqjWq7kuBHI
End of Week 5
Thank You

You might also like