Week 5 Intent Activity and SharedPreferences
Week 5 Intent Activity and SharedPreferences
• 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
• 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?
View binding
View binding is a feature that makes it easier to write code
that interacts with views.
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.)
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.)
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.)
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.
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
Returning Results
Exercise 1:
overview
WEEK: 2 Data and file storage overview
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
• ❑ 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
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
Components of a
RecyclerView
RecyclerView: The view on the screen where the list will be
displayed.
• 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.)
SharedPreferences
WEEK: 5 Preferences Using SharedPreferences class
• Definition:
• SharedPreferences is an interface used for accessing and
modifying preference data in Android.
• SharedPreferences.OnSharedPreferenceChangeListener(
): Called when a shared preference is changed, added, or
removed.
• 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
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.)
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
BroadCastReceiver
WEEK: 5 Broadcast Receivers
itself.
airplane mode.
https://www.youtube.com/watch?v=XqjWq7kuBHI
End of Week 5
Thank You