0% found this document useful (0 votes)
2 views20 pages

Unit 2 Android AD

The document covers various aspects of Android application development, including user interface layouts, the Android manifest file, styles and themes, and components like activities and services. It details different layout types such as LinearLayout, RelativeLayout, and ConstraintLayout, and explains the purpose of the AndroidManifest.xml file in defining app structure and permissions. Additionally, it discusses the significance of styles and themes for UI customization and provides code snippets for better understanding.

Uploaded by

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

Unit 2 Android AD

The document covers various aspects of Android application development, including user interface layouts, the Android manifest file, styles and themes, and components like activities and services. It details different layout types such as LinearLayout, RelativeLayout, and ConstraintLayout, and explains the purpose of the AndroidManifest.xml file in defining app structure and permissions. Additionally, it discusses the significance of styles and themes for UI customization and provides code snippets for better understanding.

Uploaded by

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

Unit 2

Android application development


1) what is user interface explain type of layout in Android any 5
2) write a short note Android manifest files
3) define style and theme and explain any two things given code snippet
4) what is mean explain type of mean in Android
5) what is view class and explain recycler view and list view along with diagram
6) state and explain screen navigation and autotextcompleteView
7) write a short note on shared preference in Android Kotli
8) what is storage in Android explain types of storage in real module give suitable exam
9) difference between SQLite database and Firebase real time database
10) difference between internal and external storage
11) what is content provide and explain with example

1) what is user interface explain type of layout in Android any 5

In Android development, the User Interface (UI) refers to the visual elements and interactions
that allow users to interact with the app. It includes buttons, text fields, images, navigation
components, and more, all designed to provide a smooth and intuitive user experience.
There are several types of layouts in Android that help structure the UI elements. These layouts
define how the views (like buttons, text fields, etc.) are positioned on the screen. Here are five
common types of layouts in Android:
1. LinearLayout
 Description: A LinearLayout arranges its child views either vertically or horizontally in a
single row or column.
 Usage: It's commonly used when you want to display UI elements in a simple, linear
order.
 Example:
 <LinearLayout
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <Button android:text="Button 1" />
 <Button android:text="Button 2" />
 </LinearLayout>
2. RelativeLayout
 Description: A RelativeLayout allows you to position views relative to each other. Views
can be aligned to the top, bottom, left, right, center, etc., of other views or the parent
layout.
 Usage: It’s ideal for creating flexible and complex layouts where elements depend on
the position of other elements.
 Example:
 <RelativeLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <Button
 android:id="@+id/button1"
 android:text="Button 1"
 android:layout_alignParentTop="true" />

 <Button
 android:id="@+id/button2"
 android:text="Button 2"
 android:layout_below="@id/button1" />
 </RelativeLayout>
3. ConstraintLayout
 Description: A ConstraintLayout provides a flexible and efficient way to create complex
layouts. You can position views relative to each other with constraints (e.g., align top,
bottom, left, right, etc.).
 Usage: It's often used for responsive UIs, and it is recommended for new Android UI
designs because of its efficiency and flexibility.
 Example:
 <androidx.constraintlayout.widget.ConstraintLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <Button
 android:id="@+id/button1"
 android:text="Button 1"
 app:layout_constraintTop_toTopOf="parent"
 app:layout_constraintStart_toStartOf="parent" />

 <Button
 android:id="@+id/button2"
 android:text="Button 2"
 app:layout_constraintTop_toBottomOf="@id/button1"
 app:layout_constraintStart_toStartOf="parent" />
 </androidx.constraintlayout.widget.ConstraintLayout>
4. FrameLayout
 Description: A FrameLayout is used to display a single child view at a time. It is
commonly used for fragments or to display one view that occupies the entire space of
the layout.
 Usage: Ideal when you only need to show one item at a time, such as in cases with full-
screen images or videos.
 Example:
 <FrameLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <Button android:text="Button 1" />
 </FrameLayout>
5. GridLayout
 Description: A GridLayout allows you to place child views in a grid-like structure, with
rows and columns. It gives you flexibility to define where each element will appear in the
grid.
 Usage: It's useful when you need a UI element to be arranged in rows and columns, like
a calculator or image gallery.
 Example:
 <GridLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:columnCount="2">

 <Button android:text="Button 1" />
 <Button android:text="Button 2" />
 <Button android:text="Button 3" />
 <Button android:text="Button 4" />
 </GridLayout>

2) write a short note Android manifest files


Android Manifest File in Android
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in
the root directory of its project hierarchy. The manifest file is an important part of our app
because it defines the structure and metadata of our application, its components, and its
requirements. This file includes nodes for each of the Activities, Services, Content Providers,
and Broadcast Receivers that make the application, and using Intent Filters and Permissions
determines how they coordinate with each other and other applications.
The manifest file also specifies the application metadata, which includes its icon, version
number, themes, etc., and additional top-level nodes can specify any required permissions, and
unit tests, and define hardware, screen, or platform requirements. The manifest comprises a
root manifest tag with a package attribute set to the project’s package.
1. manifest
The main component of the AndroidManifest.xml file is known as manifest. Additionally, the
packaging field describes the activity class’s package name. It must contain an <application>
element with the xmlns:android and package attribute specified.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.geeksforgeeks">

<!-- manifest nodes -->

<application>

</application>

</manifest>
2. uses-sdk
It is used to define a minimum and maximum SDK version by means of an API Level integer
that must be available on a device so that our application functions properly, and the target SDK
for which it has been designed using a combination of minSdkVersion, maxSdkVersion, and
targetSdkVersion attributes, respectively. It is contained within the <manifest> element.
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="27" />
3. uses-permission
It outlines a system permission that must be granted by the user for the app to function properly
and is contained within the <manifest> element. When an application is installed (on Android 5.1
and lower devices or Android 6.0 and higher), the user must grant the application permissions.
<uses-permission
android:name="android.permission.CAMERA"
android:maxSdkVersion="18" />
4. application
A manifest can contain only one application node. It uses attributes to specify the metadata for
your application (including its title, icon, and theme). During development, we should include a
debuggable attribute set to true to enable debugging, then be sure to disable it for your release
builds. The application node also acts as a container for the Activity, Service, Content Provider,
and Broadcast Receiver nodes that specify the application components. The name of our
custom application class can be specified using the android:name attribute.
<application
android:name=".GeeksForGeeks"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@drawable/gfgIcon"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@android:style/Theme.Light"
android:debuggable="true"
tools:targetApi="31">
<!-- application nodes -->

</application>
5. uses-library
It defines a shared library against which the application must be linked. This element instructs
the system to add the library’s code to the package’s class loader. It is contained within the
<application> element.
<uses-library
android:name="android.test.runner"
android:required="true" />
6. activity
The Activity sub-element of an application refers to an activity that needs to be specified in the
AndroidManifest.xml file. It has various characteristics, like label, name, theme, launchMode,
and others. In the manifest file, all elements must be represented by <activity>. Any activity that
is not declared there won’t run and won’t be visible to the system. It is contained within the
<application> element.
<activity
android:name=".MainActivity"
android:exported="true">
</activity>
7. intent-filter
It is the sub-element of activity that specifies the type of intent to which the activity, service, or
broadcast receiver can send a response. It allows the component to receive intents of a certain
type while filtering out those that are not useful for the component. The intent filter must contain
at least one <action> element.
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
8. action
It adds an action for the intent-filter. It is contained within the <intent-filter> element.
<action android:name="android.intent.action.MAIN" />
9. category
It adds a category name to an intent-filter. It is contained within the <intent-filter> element.
<category android:name="android.intent.category.LAUNCHER" />
10. uses-configuration
The uses-configuration components are used to specify the combination of input mechanisms
that are supported by our application. It is useful for games that require particular input controls.
<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
android:reqKeyboardType=”qwerty”/>

<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
android:reqKeyboardType=”twelvekey”/>
11. uses-features
It is used to specify which hardware features your application requires. This will prevent our
application from being installed on a device that does not include a required piece of hardware
such as NFC hardware, as follows:
<uses-feature android:name=”android.hardware.nfc” />
12. permission
It is used to create permissions to restrict access to shared application components. We can
also use the existing platform permissions for this purpose or define your own permissions in
the manifest.
<permission
android: name=”com.paad.DETONATE_DEVICE”
android:protectionLevel=“dangerous”
android:label=”Self Destruct”
android:description=”@string/detonate_description”>
</permission>

3) define style and theme and explain any two things given code snippet
Style and Theme in Android
In Android development, styles and themes are used to define the visual appearance of the
app's UI components. Both allow developers to customize the look and feel of the application in
a more organized and reusable manner.
Style:
A style in Android is a collection of properties that define the appearance of a single view (such
as a Button, TextView, etc.). It allows you to define various visual attributes such as colors,
fonts, padding, and size that can be applied to individual elements in your app.
 Example:
 <style name="CustomTextStyle">
 <item name="android:textColor">@android:color/black</item>
 <item name="android:textSize">18sp</item>
 <item name="android:fontFamily">sans-serif</item>
 </style>
In this example, the CustomTextStyle style sets the text color to black, text size to 18sp, and
font family to sans-serif. You can apply this style to any TextView or similar UI element.

Theme:
A theme is a broader version of a style. It is a collection of styles that can be applied globally to
an entire activity or application. Themes affect the overall appearance of the UI, including
background color, text color, buttons, and other components. They help maintain a consistent
look across the entire app.
 Example:
 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
 <item name="android:windowBackground">@color/background</item>
 <item name="android:textColorPrimary">@android:color/black</item>
 </style>
In this example, AppTheme defines the overall theme for the app. It is based on the
Theme.AppCompat.Light.DarkActionBar and customizes the window background and primary
text color for the entire app or activity.

Two Things Explained:


1. Applying Style to a UI Element:
In Android, you can apply a style to individual UI elements to customize their appearance. For
instance, if you want to apply the CustomTextStyle to a TextView, you would do it like this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
style="@style/CustomTextStyle"/>
Here, the TextView will have the black text color, 18sp text size, and sans-serif font family as
defined in the CustomTextStyle style.

2. Setting a Theme for an Activity or Application:


A theme can be applied to an entire activity or the whole application, affecting all UI
components within it. For example, you can set a theme in your AndroidManifest.xml to apply it
globally to all activities in your app:
<application
android:theme="@style/AppTheme">
...
</application>
This will apply the AppTheme to all the activities in the app, ensuring a consistent look and feel.
You can also apply a theme to a specific activity:
<activity android:name=".MainActivity"
android:theme="@style/AnotherTheme">
</activity>
This ensures that the theme customization, such as text color, background, and other visual
attributes, will be applied across the entire activity.

4) what is mean explain type of mean in Android


If you meant "mean" in Android development, perhaps you’re referring to something like
"means" (types) or perhaps the "App Component's" purpose (such as activities, services,
etc.). If that's the case, here’s a bit of an explanation:
If you’re asking about "types" or "meanings" in Android (such as types of UI components or
core concepts), here are a few possible topics:
1. Android App Components: These are the core building blocks of an Android app. They
include:
o Activities: A single screen with a user interface (UI).
o Services: Components running in the background to perform long-running
operations.
o Broadcast Receivers: Listen for system-wide broadcast messages (e.g., a
network change).
o Content Providers: Manage app data and provide access to it for other apps.
2. Android Layouts: Different layouts help arrange UI elements within an app. Examples
include LinearLayout, RelativeLayout, FrameLayout, etc.
3. Android Themes and Styles: This refers to the visual styling of UI elements (as
mentioned previously).
4. Permissions and Features: Types of permissions (like Internet access) or hardware
features (camera, GPS) declared in the Android Manifest file.

If You Mean the Statistical "Mean" (Average) in Android:


If you meant “mean” in the statistical sense (i.e., average), you might be referring to how to
compute the mean of a set of numbers in an Android app, perhaps when working with data or
performing calculations.
Here's an example of how to calculate the mean (average) of an array of numbers in Android
using Java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

int[] numbers = {5, 10, 15, 20, 25};


double mean = calculateMean(numbers);
Log.d("Mean", "The mean is: " + mean);
}

private double calculateMean(int[] numbers) {


int sum = 0;
for (int num : numbers) {
sum += num;
}
return (double) sum / numbers.length;
}
}
In this code:
 We define an array of numbers.
 The calculateMean method computes the average (mean) by summing all numbers and
dividing by the number of elements in the array.

5) what is view class and explain recycler view and list view along with diagram
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and
ListView. It is an improvement on both of them and can be found in the latest v-7 support
packages. It has been created to make possible construction of any lists with XML layouts as an
item which can be customized vastly while improving on the efficiency of ListViews and
GridViews. This improvement is achieved by recycling the views which are out of the visibility of
the user.
For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2,
and 3 would be cleared from the memory to reduce memory consumption.
Let us check, Android RecyclerView with a simple example.
Example: An Android Application showing the Exam Schedule

To implement a basic RecyclerView three sub-parts are needed to be constructed which offer
the users the degree of control they require in making varying designs of their choice.
1. The Card Layout: The card layout is an XML layout which will be treated as an item for
the list created by the RecyclerView.
2. The ViewHolder: The ViewHolder is a java class that stores the reference to the card
layout views that have to be dynamically modified during the execution of the program
by a list of data obtained either by online databases or added in some other way.
3. The Data Class: The Data class is a custom java class that acts as a structure for
holding the information for every item of the RecyclerView.
Step by Step to Create RecyclerView
Step 1: Create new project
 Click on File, then New => New Project.
 Choose “Empty Activity” for the project template.
 Select language as Kotlin.
 Select the minimum SDK(According to the application needs).
Step 2: Creating Layout for the Application
Layouts are important part of the Android Applications. This Application will need two main
layouts as mentioned below:
A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items,
with each item positioned one below the other. Using an adapter, items are inserted into the list
from an array or database efficiently. For displaying the items in the list method setAdaptor() is
used. The setAdaptor() method binds the adapter with the ListView.
ListView in Android is a ViewGroup that is used to display the list of items in multiple rows and
contains an adapter that automatically inserts the items into the list dynamically. The main
purpose of the adapter is to retrieve data from an array or database and dynamically insert each
item into the list for the desired result.
Some Important XML Attributes of ListView

Attribute Description

android:divider A color or drawable to separate list items.

android:dividerHeight Divider’s height.

Reference to an array resource that will populate


android:entries
the ListView.

When set to false, the ListView will not draw the


android:footerDividersEnabled
divider before each footer view.

android:headerDividersEnabled When set to false, the ListView will not draw the
Attribute Description

divider before each header view.

6) state and explain screen navigation and autotextcompleteView


Screen Navigation in Mobile Development
Screen navigation refers to how a user moves between different screens or views in a mobile
app. It is a fundamental part of user experience (UX) design because it dictates how users
interact with the app's interface, how they move from one screen to another, and how intuitive
the overall navigation feels.
In mobile development (especially in frameworks like Android and iOS), screen navigation
typically involves:
1. Activities (in Android) or ViewControllers (in iOS): These are the individual screens
or views the user interacts with.
2. Navigation Components: These are mechanisms that handle transitions from one
screen to another. Examples include:
o Explicit Intents (Android) for starting an activity.
o Navigation Controllers (iOS) for managing the navigation stack of screens.
3. Navigation Patterns:
o Push Navigation: This involves placing a new screen on top of the current one
(e.g., tapping a button leads to a new screen).
o Pop Navigation: This involves going back to the previous screen, typically by
pressing a back button or swipe gesture.
o Tab-based Navigation: The app has a set of tabs that represent different
sections, allowing users to jump between them.
o Drawer Navigation: A side menu that slides in, allowing users to access
different sections.
4. Navigational Tools:
o Back Stack: A stack of screens where users can go back to previous screens
(common in Android with the back button).
o Navigation Bar: A toolbar that provides buttons to navigate within the app.
o Transitions/Animations: These are visual effects that occur during navigation
between screens to enhance the user experience.

AutoTextCompleteView
AutoTextCompleteView is a widget commonly used in mobile development (particularly in
Android) to provide real-time suggestions for users as they type into a text input field. It
enhances the user experience by helping users quickly find the information or options they need
without having to type everything out.
Key Features of AutoTextCompleteView:
1. Real-time Suggestions: As the user types, the view dynamically suggests possible
completions based on the entered text.
2. Searchable Dataset: The suggestions are typically pulled from a predefined set of data,
such as a list of names, cities, or terms. The data is filtered based on the user's input.
3. User-Friendly Interface: The widget typically shows a dropdown or list of suggestions
that the user can scroll through and select from. It can make data entry much faster.
4. Use Cases:
o Search Bars: Offering suggestions while typing search queries.
o Address Input: Autocomplete addresses as the user types.
o Email or Username Fields: Autocompleting email addresses or usernames
based on previous inputs.
Example of AutoTextCompleteView in Android:
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, data);
autoCompleteTextView.setAdapter(adapter);
In this example:
 AutoCompleteTextView is a widget for user input.
 ArrayAdapter is used to supply the suggestions (like a list of strings).
 The adapter connects the input field with the dataset (a list of strings, such as possible
locations, emails, etc.).

7) write a short note on shared preference in Android Kotli


One of the most Interesting Data Storage options Android provides its users is Shared
Preferences. Shared Preferences is the way in which one can store and retrieve small
amounts of primitive data as key/value pairs to a file on the device storage such as String, int,
float, Boolean that make up your preferences in an XML file inside the app on the device
storage. Shared Preferences can be thought of as a dictionary or a key/value pair. For
example, you might have a key being “username” and for the value, you might store the user’s
username. And then you could retrieve that by its key (here username). You can have a simple
shared preference API that you can use to store preferences and pull them back as and when
needed.
Shared Preferences are suitable for different situations. For example, when the user’s settings
need to be saved or to store data that can be used in different activities within the app. As you
know, onPause() will always be called before your activity is placed in the background or
destroyed, So for the data to be saved persistently, it’s preferred to save it in onPause(), which
could be restored in onCreate() of the activity. The data stored using shared preferences are
kept private within the scope of the application. However, shared preferences are different from
that activity’s instance state.
How to Create Shared Preferences?
The first thing we need to do is to create one shared preferences file per app. So name it with
the package name of your app- unique and easy to associate with the app. When you want to
get the values, call the getSharedPreferences() method. Shared Preferences provide modes of
storing the data (private mode and public mode). It is for backward compatibility- use
only MODE_PRIVATE to be secure.
public abstract SharedPreferences getSharedPreferences (String name, int mode)
This method takes two arguments, the first being the name of the SharedPreference(SP) file
and the other is the context mode that we want to store our file in.
 MODE_PUBLIC will make the file public which could be accessible by other applications
on the device
 MODE_PRIVATE keeps the files private and secures the user’s data.
 MODE_APPEND is used while reading the data from the SP file.
Nested classes of Shared Preferences
1. 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.
2. 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.
Functions of Shared Preferences
1. contains(String key): This method is used to check whether the preferences contain a
preference.
2. 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.
3. getAll(): This method is used to retrieve all values from the preferences.
4. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean
value from the preferences.
5. getFloat(String key, float defValue): This method is used to retrieve a float value from
the preferences.
6. getInt(String key, int defValue): This method is used to retrieve an int value from the
preferences.
7. getLong(String key, long defValue): This method is used to retrieve a long value from
the preferences.
8. getString(String key, String defValue): This method is used to retrieve a String value
from the preferences.
9. getStringSet(String key, Set defValues): This method is used to retrieve a set of String
values from the preferences.
10. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPrefere
ncechangeListener listener): This method is used to register a callback to be invoked
when a change happens to a preference.
11. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPrefe
rencechangeListener listener): This method is used to unregister a previous callback.

8) what is storage in Android explain types of storage in real module give suitable exam
Storage in Android
In Android, storage refers to the system's ability to persistently store data, whether it is user
data, application data, or files. Android provides several options for storing data on a device,
each serving different use cases.
There are two primary types of storage in Android:
1. Internal Storage: Private to the app and not accessible by other apps.
2. External Storage: Typically accessible by other apps and users (like SD cards or
external drives), though with restricted permissions on modern Android versions.
Types of Storage in Android
1. Internal Storage:
o Definition: Data stored in internal storage is private to the app and cannot be
accessed by other apps or the user without root access. This storage is typically
used for sensitive or private data that should not be shared.
o Location: Files are stored in the app's private directory
(/data/data/com.example.app/files).
o Usage: Ideal for storing application-specific files that shouldn't be modified by the
user or other apps.
o Example: Storing user preferences, small databases, or encrypted data.
Example in Kotlin:
// Writing to internal storage
val filename = "myfile.txt"
val fileContents = "Hello, World!"
openFileOutput(filename, Context.MODE_PRIVATE).use {
it.write(fileContents.toByteArray())
}

// Reading from internal storage


val fileInputStream: FileInputStream = openFileInput(filename)
val content = fileInputStream.bufferedReader().use { it.readText() }
println(content) // Output: Hello, World!
2. External Storage:
o Definition: External storage refers to storage locations that can be accessed
outside of the app, such as an SD card or USB storage. External storage can be
both public (available to all apps) and private (restricted to your app, but still
located in a shared external space).
o Location: Public external storage is typically located in directories like
/storage/emulated/0/, /sdcard/, or similar paths.
o Usage: Used for storing large files (e.g., images, audio, or video) that need to be
shared with other apps or accessed by the user.
o Permissions: In recent Android versions (especially Android 6.0+), apps require
specific permissions (READ_EXTERNAL_STORAGE and
WRITE_EXTERNAL_STORAGE) to access external storage. From Android 11
onward, Google introduced Scoped Storage, which limits access to certain
directories.
Example in Kotlin (using external storage with permission check):
// Writing to external storage
val file = File(Environment.getExternalStorageDirectory(), "myfile.txt")
file.writeText("Hello from external storage!")
// Reading from external storage
val content = file.readText()
println(content) // Output: Hello from external storage!
Permissions in AndroidManifest.xml (for external storage):
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3. Shared Preferences:
o Definition: Shared Preferences provide a way to store key-value pairs in a
persistent file, often used to store app settings or small pieces of data that need
to be retained across app sessions.
o Location: Data is stored in a key-value format in a private file for the app
(typically in /data/data/com.example.app/shared_prefs).
o Usage: Storing user settings, flags (e.g., first-time launch), or other small
configurations.
Example in Kotlin:
// Storing data in SharedPreferences
val sharedPref = getSharedPreferences("MyPrefs", MODE_PRIVATE)
with(sharedPref.edit()) {
putString("username", "john_doe")
putInt("age", 30)
apply()
}

// Retrieving data from SharedPreferences


val username = sharedPref.getString("username", "default_username")
val age = sharedPref.getInt("age", 0)
println("Username: $username, Age: $age")
4. SQLite Database:
o Definition: SQLite is a lightweight relational database management system that
is built into Android. It is used for storing structured data that requires querying or
filtering.
o Location: The database files are stored in the app's private storage (typically
/data/data/com.example.app/databases).
o Usage: Ideal for storing complex data like user information, transactions, or other
structured data that may need querying, filtering, and sorting.
Example in Kotlin:
// Using SQLiteOpenHelper to manage database creation and versioning
class DBHelper(context: Context) : SQLiteOpenHelper(context, "MyDatabase", null, 1) {
override fun onCreate(db: SQLiteDatabase?) {
db?.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age
INTEGER)")
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {


// Handle database upgrade
}
}

// Inserting data into the database


val dbHelper = DBHelper(context)
val db = dbHelper.writableDatabase
val values = ContentValues().apply {
put("name", "John")
put("age", 30)
}
db.insert("users", null, values)

// Retrieving data from the database


val cursor = db.query("users", arrayOf("id", "name", "age"), null, null, null, null, null)
if (cursor.moveToFirst()) {
val name = cursor.getString(cursor.getColumnIndex("name"))
val age = cursor.getInt(cursor.getColumnIndex("age"))
println("Name: $name, Age: $age")
}
cursor.close()
5. Cache Storage:
o Definition: Cache storage allows temporary storage of data that is frequently
accessed and can be easily regenerated or discarded.
o Location: Typically, the cache files are stored in the app’s private cache
directory (/data/data/com.example.app/cache).
o Usage: Useful for caching images, API responses, or other data that can be
quickly recreated.
Example in Kotlin:
val cacheDir = cacheDir
val file = File(cacheDir, "cached_data.txt")
file.writeText("This is cached data.")
val content = file.readText()
println(content) // Output: This is cached data.
on the nature of the data, its accessibility requirements, and how long it needs to be stored.
9) Difference between SQLite database and Firebase real time database
Feature SQLite Database Firebase Realtime Database
Type of Database Relational Database (SQL-based) NoSQL (JSON-based)
Tables with rows and columns JSON tree structure (Hierarchical
Data Structure
(Structured data) data)
Stored locally on the device (in the Stored in the cloud (Google's Firebase
Storage Location
app's private storage) infrastructure)
Synchronization Data is stored locally, no automatic Real-time sync between app and
sync with cloud. cloud. Data is updated across all
Feature SQLite Database Firebase Realtime Database
clients immediately.
Offline Support Fully supports offline data storage. Supports offline usage with local
cache and sync when the device is
online.
Data Querying Limited querying, primarily relies on
SQL queries can be executed to
hierarchical structure and basic
retrieve, filter, and sort data.
operations.
Limited to local storage size (device Scalable, as it is cloud-based and can
Scalability
storage capacity). handle large datasets.
Performance Performance depends on the size Highly optimized for real-time data, but
of the database and the complexity performance depends on network
of queries. speed and cloud infrastructure.
Data Consistency Data consistency is guaranteed; Eventually consistent, and data is
supports transactions for ACID synchronized in real-time across all
properties. connected clients.
Security is handled at the app level Firebase offers built-in security rules to
Security
(e.g., encrypted storage). control data access.
Data Backup & No built-in backup solution; must be Firebase provides automatic backups
Recovery handled manually. and data recovery options.
Not available; must use custom Native support for real-time updates
Real-Time Updates
solutions to sync data. and live data synchronization.
Use Case Suitable for local, structured, offline Suitable for cloud-based, real-time
storage needs (e.g., app settings, applications with dynamic data (e.g.,
local caching). chat apps, collaborative apps).
Simple to implement; requires Requires Firebase setup, including
Complexity of
adding SQLiteOpenHelper and creating a Firebase project and
Setup
creating tables. configuring Firebase SDK.
Cost Firebase Realtime Database may
No cost, as it's stored locally on the
incur costs based on data usage,
device.
storage, and operations.
10) difference between internal and external storage
Feature Internal Storage External Storage
Data is private to the app and not
Data is generally accessible by other
Accessibility accessible by other apps or the
apps and can be accessed by the user.
user (unless rooted).
Located in the app's private
Storage Typically located in public directories
directory
Location (/storage/emulated/0/, /sdcard/).
(/data/data/package_name/).
Permissions No special permissions required Requires explicit permissions
to access. (READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE) in
Feature Internal Storage External Storage
AndroidManifest.xml.
Privacy Data is private to the app. Only Data is public or accessible by other
the app can read/write to this apps (unless stored in private external
storage. storage).
Generally larger than internal storage,
Size Limited to the device’s internal
especially with SD cards or external
Limitation storage size, which varies.
drives.
Persistence Data is stored persistently even
Data can be lost if the external storage
after the app is closed or the
is removed or unmounted.
device is restarted.
Typically faster, as it is stored Slower than internal storage (depending
Performance
directly on the device. on the device's external storage speed).
Data Security Data is more secure because it’s Data can be accessed by other apps or
not easily accessible by other the user, and is more vulnerable to
apps or users. malicious apps or users.
Suitable for storing large files (e.g.,
Suitable for storing app-specific,
media files like images, videos, and
Use Case sensitive data (e.g., user settings,
documents) or data that can be shared
small databases).
between apps.
Read/Write Faster read/write operations as Slower, especially with removable
Speed it’s stored on the device. storage (e.g., SD cards).
Examples - User settings- App data
- Photos- Videos- Downloaded content-
(databases, preferences)-
Shared app data
Encrypted files
Accessible only when the external
Access While Always accessible even when the
storage is available and mounted (e.g.,
Offline device is offline.
SD card, USB drive).
No risk of data loss unless the
Data Loss Risk of data loss if external storage is
app is uninstalled or the device is
Risk removed or becomes corrupted.
reset.
11) what is content provide and explain with example
In Android , Content Providers are a very important component that serves the purpose
of a relational database to store the data of applications. The role of the content provider
in the android system is like a central repository in which data of the applications are
stored, and it facilitates other applications to securely access and modifies that data
based on the user requirements. Android system allows the content provider to store the
application data in several ways. Users can manage to store the application data like
images, audio, videos, and personal contact information by storing them in SQLite
Database , in files , or even on a network . In order to share the data, content providers
have certain permissions that are used to grant or restrict the rights to other applications
to interfere with the data.
Content URI
Content URI(Uniform Resource Identifier) is the key concept of Content providers. To
access the data from a content provider, URI is used as a query string.
Looking to become an expert in Android App Development? Whether you're a student or
a professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.
Structure of a Content URI: content://authority/optionalPath/optionalID
Details of different parts of Content URI:
 content:// – Mandatory part of the URI as it represents that the given URI is a
Content URI.
 authority – Signifies the name of the content provider like contacts, browser, etc.
This part must be unique for every content provider.
 optionalPath – Specifies the type of data provided by the content provider. It is
essential as this part helps content providers to support different types of data
that are not related to each other like audio and video files.
 optionalID – It is a numeric value that is used when there is a need to access a
particular record.
If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based URI.
Operations in Content Provider
Four fundamental operations are possible in Content Provider
namely Create , Read , Update , and Delete . These operations are often termed as CRUD
operations .
 Create: Operation to create data in a content provider.
 Read: Used to fetch data from a content provider.
 Update: To modify existing data.
 Delete: To remove existing data from the storage.
Working of the Content Provider
UI components of android applications like Activity and Fragments use an
object CursorLoader to send query requests to ContentResolver. The ContentResolver
object sends requests (like create, read, update, and delete) to the ContentProvider as a
client. After receiving a request, ContentProvider process it and returns the desired
result. Below is a diagram to represent these processes in pictorial form.

Creating a Content Provider


Following are the steps which are essential to follow in order to create a Content
Provider:
 Create a class in the same directory where the that MainActivity file resides and
this class must extend the ContentProvider base class.
 To access the content, define a content provider URI address.
 Create a database to store the application data.
 Implement the six abstract methods of ContentProvider class.
 Register the content provider in AndroidManifest.xml file using <provider> tag .

You might also like