Unit - 5
Unit - 5
PROVIDERS
What are Content
Providers?
• Requirements:
• APK File (Can be downloaded via email, website, USB, or cloud storage).
• Enable "Unknown Sources" (Required for Android 7 and below).
• Enable "Install Unknown Apps" (For Android 8 and above).
Pros: Cons:
• Quick and simple. • Security risks if installing from untrusted sources.
• No developer account required. • Users need to manually enable unknown sources.
• No Play Store approval process. • No automatic updates (must reinstall manually).
STEPS TO INSTALL APK MANUALLY
• Transfer the APK File
• Use USB Cable, Bluetooth, Cloud Storage (Google Drive, Dropbox, etc.), or Email to send the
APK to the target device.
• Enable Installation from Unknown
• Sources Android 7 & Below:
• Go to Settings > Security > Unknown Sources → Enable it.
• Example Code:
• Setting URI:
• emailIntent.setData(Uri.parse("mailto:"));
• Setting Type:
• emailIntent.setType("text/plain");
ADDING EXTRA DATA
• Example Code:
• emailIntent.putExtra(Intent.EXTRA_EMAIL, new
String[]{"[email protected]"});
• emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject
Line");
• emailIntent.putExtra(Intent.EXTRA_TEXT, "Message Body");
ADDITIONAL EMAIL EXTRAS
• Steps:
• 1. Create a new Android project
• 2. Modify MainActivity.java
• 3. Add a button in activity_main.xml
• 4. Define string values in res/values/strings.xml
• 5. Update AndroidManifest.xml
• 6. Run and test on a device
EXAMPLE UI (ACTIVITY_MAIN.XML)
EXAMPLE CODE (MAINACTIVITY.JAVA)
EXAMPLE CODE (MAINACTIVITY.JAVA)
OUTPUT:
RUNNING THE APPLICATION
Getting location data refers to the process of retrieving the geographical position of a
device (smartphone, tablet, or any GPS-enabled hardware). This data is essential for
applications that provide navigation, tracking, weather updates, geotagging, and location-
based services.
What is location API in
Android?
The Location API in Android helps apps find the user's current
location using GPS, Wi-Fi, or mobile networks. It allows apps like
Google Maps, ride-hailing apps, and weather apps to determine
where you are.
•Foreground Location Access: The app
fetches real-time location when it's open.
•Background Location Access: The app
tracks location even when running in the
Methods of Fetching
background (requires special permissions).
Location Data •Geofencing: Triggers events when the
user enters or exits predefined geographical
areas.
Location Object Method
float getAccuracy()
2
Get the estimated accuracy of this location, in meters.
double getLatitude()
3
Get the latitude, in degrees.
double getLongitude()
4
Get the longitude, in degrees.
float getSpeed()
5
Get the speed if it is available, in meters/second over ground.
Get the Current Location
• Delivery Apps:
Track the location of delivery personnel and vehicles, and provide real-time updates
to customers.
• Travel Apps:
Recommend nearby restaurants, attractions, and events based on the user's current
location.
• Emergency Services:
Track the location of users in distress and dispatch appropriate help.
Permissions Considerations
Requires ACCESS_FINE_LOCATION and
ACCESS_COARSE_LOCATION permissions in AndroidManifest.xml.
Example Use Cases
Implementation
Working of Getting
Location Data
Retrieving location data in a mobile application
involves multiple components working
together, including sensors, APIs, and network
services.
Programming
Example for
Getting Location Data
Android Manifest.xml
Activity_main.xml
MainActivity.java
build.gradle.kts (:app)
OUTPUT
Chapter 11 - Networking
• AndroidManifest.xml:
<uses-permission
android:name="android.permission.INTERNET"/
>
Downloading Text
• Key steps:
• 1. Open connection
• 2. Read input stream
• 3. Update UI in AsyncTask
• new
DownloadTextTask().execute("http://example.
com/data.txt");
DownloadTextTask Example
• Using AsyncTask to download text in background:
Bitmap bitmap =
BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
Downloading Plain Text
• Example snippet:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Document doc = builder.parse(url.openStream());
Consuming JSON Services
• - Use JSONArray and JSONObject
• - Parse response and show in UI
try {
// Network logic
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) inputStream.close();
}
AsyncTask Structure
• Basic structure for network operations:
2. EVOLUTION OF SMS
INDEX 3. SmsManager
Function Description
sendTextMessage(String destinationAddress, String scAddress,
sendTextMessage() String text, PendingIntent sentIntent, PendingIntent deliveryIntent,
long messageId)
<ImageView
android:id="@+id/imageView"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginTop="60dp"
android:src="@drawable/gfg_icon" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number:"
android:width="165sp"
android:textSize="18sp" />
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter number"
android:inputType="phone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:orientation="horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message to be Sent:"
android:width="165sp"
android:textSize="18sp" />
<EditText
android:id="@+id/editText2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:gravity="top|start"
android:hint="Enter message"
android:inputType="textMultiLine" />
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="SEND" />
</LinearLayout>
package com.example.gfg;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
Note: For running application in Android device enable the SMS permission for the app.
Go to permissions->SMS->YourApp and enable permission.
SQLite in Mobile
Apps
A comprehensive guide to using SQLite for Android
development.
01
SQLite Overview
What is SQLite?
SQLite is a C library that provides a lightweight disk-based
database. Unlike other databases, it does not require a separate
server process and allows access to the database file directly. It
is popular for mobile applications because of its simplicity and
efficiency in managing data locally on devices.
Key Features of SQLite
SQLite features include a self-contained setup, zero
configuration, and a serverless architecture. It supports
transactional ACID properties, offers full-text search, and allows
for multiple simultaneous writes. Its compact size makes it
ideal for mobile applications where system resources are
limited.
SQLite in Mobile Development
SQLite is widely used in mobile development due to its light
footprint and efficiency. It allows developers to store data locally
within the app with minimal overhead. Many Android apps utilize
SQLite for offline data storage and quick access. The simplicity of
integrating SQLite in Android Studio via the Room persistence
library enhances its appeal, making it easier to manage databases
and data interactions simply and effectively.
02
Working with SQLite
Database Creation
Creating a database in SQLite involves defining the structure
using SQL commands. Android Studio provides several methods
to create a SQLite database, either through raw SQL commands
or using the Room library, which abstracts much of the
complexity. Developers can define entities, DAOs, and database
versions, enabling seamless migrations and updates for data
structures as apps evolve.
Methods in SQLite
onCreate(SQLiteDatabase db)
• Called automatically when the database is first created.
• Used to define the schema, i.e., create tables using SQL commands.
• Only runs once unless the database is deleted or version is updated.
getReadableDatabase()
• Returns a read-only version of the database.
• Useful when only data retrieval is needed and writing is not required.
Cursor.getString(index) / getInt(index)
• Retrieves the value at a specified column index in the current row.
Toast.makeText(...)
• Displays a short message on the screen.
• Often used to notify users about success/failure of a database operation.
03
In and Out of
SQLite
In SQLite (Inside
the App)
Definition:
"In SQLite" refers to how SQLite is used internally within an Android
application to store, manage, and retrieve data locally on the device using
Java and Android APIs.
Key Points:
•Involves creating, reading, updating, and deleting (CRUD) data using Java.
•The database resides in the app’s internal storage.
•Managed using SQLiteOpenHelper, SQLiteDatabase, and Cursor.
•Data is accessed and manipulated during app runtime.
•No need for internet connection — fully offline and embedded.
Out of SQLite
(Outside the App)
Definition:
"Out of SQLite" refers to external access or interaction with the SQLite
database file outside the Android application, mainly for debugging,
analyzing, backing up, or restoring the database.
Key Points:
•Accessed through tools like Android Device File Explorer, ADB, or SQLite
browser tools.
•You can export or import .db files.
•Useful for viewing database structure, inspecting records, or troubleshooting.
•Can also be used to preload data into the app before shipping.
Data Binding in Android
Data Binding in Android allows UI components to directly
connect to data sources, making it easier to update and
manage data displayed in the app. By utilizing LiveData and
ViewModel in conjunction with Room, developers can
effortlessly propagate changes between the database and UI.
This technique improves responsiveness and reduces
boilerplate code, enhancing the overall development
experience.
AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</manifest>
MainActivity.java file
package com.mad.program14;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText Name, Age;
Button Save, Retrieve;
TextView Result;
DatabaseHelper databaseHelper;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = findViewById(R.id.name);
Age = findViewById(R.id.age);
Save = findViewById(R.id.save);
Retrieve = findViewById(R.id.retrieve);
Result = findViewById(R.id.result);
databaseHelper = new DatabaseHelper(this);
sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Save.setOnClickListener(v -> {
String name = Name.getText().toString().trim();
String ageStr = Age.getText().toString().trim();
if (name.isEmpty() || ageStr.isEmpty()) {
Toast.makeText(this, "Please enter both Name and Age", Toast.LENGTH_SHORT).show();
return;
}
try {
int age = Integer.parseInt(ageStr);
boolean isInserted = databaseHelper.insertUser(name, age);
sharedPreferences.edit().putString("name", name).putInt("age", age).apply();
Toast.makeText(this, isInserted ? "Data Saved Successfully!" : "Failed to Save Data",
Toast.LENGTH_SHORT).show();
if (isInserted) {
Name.setText("");
Age.setText("");
}
}
catch (NumberFormatException e) {
Toast.makeText(this, "Invalid Age Input", Toast.LENGTH_SHORT).show();
}
});
Retrieve.setOnClickListener(v -> {
String sharedName = sharedPreferences.getString("name", "No Name Found");
int sharedAge = sharedPreferences.getInt("age", 0);
String sqliteData = databaseHelper.getAllUsers();
if (sqliteData.isEmpty()) sqliteData = "No data found in SQLite Database.";
Result.setText("From SharedPreferences:\nName: " + sharedName + ", Age: " + sharedAge +
"\n\nFrom SQLite Database:\n" + sqliteData);
});
}
}
DatabaseHelper.java
package com.mad.program14;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertUser(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1; // Returns true if insertion is successful
}
public String getAllUsers() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
StringBuilder result = new StringBuilder();
while (cursor.moveToNext()) {
result.append("ID: ").append(cursor.getInt(0))
.append(", Name: ").append(cursor.getString(1))
.append(", Age: ").append(cursor.getInt(2))
.append("\n");
}
cursor.close();
return result.toString();
}
}