Unit-5mobile Application Development
Unit-5mobile Application Development
Using Android Data and Storage APIs, Managing data using Sqlite, Sharing Data between Applica ons with
Content Providers, Using Android Networking APIs, Using Android Web APIs, Using Android Telephony APIs,
Deploying Android Applica on to the World.
Android provides several APIs for managing and storing data, catering to various use cases like local storage, structured databases,
and cloud integra on. These APIs enable developers to create robust applica ons with efficient data management.
3. External Storage: For larger files shared with other apps or users.
6. Cloud Storage: For syncing data across devices using Firebase or other cloud solu ons.
2. Shared Preferences
editor.putString("username", "JohnDoe");
editor.putBoolean("isLoggedIn", true);
editor.apply();
3. Internal Storage
Used for private app data that is not accessible to other apps.
// Write to a file
String filename = "myfile.txt";
fos.write(fileContents.getBytes());
String line;
stringBuilder.append(line);
4. External Storage
Used for storing large files like images, videos, and documents. Requires run me permissions for Android 6.0+.
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
stringBuilder.append(line);
5. SQLite Database
@Override
db.execSQL("CREATE TABLE Users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)");
@Override
onCreate(db);
// Insert data
SQLiteDatabase db = myDatabaseHelper.getWritableDatabase();
values.put("age", 30);
// Query data
while (cursor.moveToNext()) {
cursor.close();
6. Room Database
Room is a modern abstrac on layer over SQLite, making database opera ons easier and safer.
Add Dependencies
@En ty
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "name")
@ColumnInfo(name = "age")
@Dao
@Insert
List<User> getAllUsers();
}
Create Database
7. Cloud Storage
For syncing data across devices or users, you can use Firebase or other cloud services.
2. implementa on 'com.google.firebase:firebase-database:20.3.0'
7. database.child("users").child("1").addListenerForSingleValueEvent(new ValueEventListener() {
8. @Override
11. }
12.
13. @Override
16. }
17. });
3. Op mize Performance:
o Use Room for database opera ons instead of raw SQLite.
4. Data Backup:
By understanding and leveraging Android's data and storage APIs, you can build applica ons that effec vely manage and store
user data while ensuring performance and security.
SQLite is a lightweight, embedded database engine included in Android. It allows developers to manage structured data with SQL queries. Below are the steps
and examples to manage data using SQLite.
Example
@Override
db.execSQL(CREATE_TABLE);
@Override
onCreate(db);
Example
SQLiteDatabase db = this.getWritableDatabase();
values.put("name", name);
values.put("age", age);
db.close();
}
Step 3: Query Data from the Table
Example
SQLiteDatabase db = this.getReadableDatabase();
if (cursor.moveToFirst()) {
do {
userList.add(user);
} while (cursor.moveToNext());
cursor.close();
db.close();
return userList;
Example
SQLiteDatabase db = this.getWritableDatabase();
values.put("name", newName);
values.put("age", newAge);
db.close();
}
Example
SQLiteDatabase db = this.getWritableDatabase();
db.close();
Here’s a complete example of a SQLite helper class with CRUD opera ons:
@Override
@Override
onCreate(db);
SQLiteDatabase db = this.getWritableDatabase();
values.put(COLUMN_NAME, name);
values.put(COLUMN_AGE, age);
db.close();
SQLiteDatabase db = this.getReadableDatabase();
if (cursor.moveToFirst()) {
do {
userList.add(name);
} while (cursor.moveToNext());
cursor.close();
db.close();
return userList;
}
public void updateUser(int id, String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
values.put(COLUMN_NAME, name);
values.put(COLUMN_AGE, age);
db.close();
SQLiteDatabase db = this.getWritableDatabase();
db.close();
1. Close Resources: Always close Cursor and SQLiteDatabase objects to prevent memory leaks.
2. Use Transac ons: For mul ple database opera ons, use transac ons for be er performance and consistency.
3. db.beginTransac on();
4. try {
6. db.setTransac onSuccessful();
7. } finally {
8. db.endTransac on();
9. }
10. Avoid UI Blocking: Perform database opera ons on a background thread using AsyncTask or Executor.
11. Secure Sensi ve Data: Encrypt sensi ve data stored in the database using third-party libraries like SQLCipher.
12. Use Room Database: For modern, boilerplate-free SQLite interac ons, use the Room persistence library.
By using SQLite effec vely, you can handle complex data requirements for your Android applica on.
3) Sharing Data Between Applica ons with Content Providers in Android
In Android, Content Providers are used to share data between different applica ons. A content provider acts as an intermediary that facilitates data access and
sharing while enforcing access control. Content Providers are typically used for accessing data in a structured format, such as in a database, file system, or other
content sources.
A Content Provider is an interface for connec ng one applica on with data stored in another applica on. It exposes a standardized interface for querying and
modifying data, which can be accessed by other apps through URI (Uniform Resource Iden fier).
Enforce security policies by restric ng which apps can access or modify the data.
Managing custom app data and exposing it for other apps to use.
A Content Provider is implemented by extending the ContentProvider class. It requires the following methods:
1. onCreate(): Ini alizes the content provider. It’s called when the provider is first accessed.
6. getType(): Returns the MIME type of the data at the given URI.
Below is an example to create a simple Content Provider for managing a list of books in an app.
Create a class that extends ContentProvider and implement the required methods.
BookContentProvider.java
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
@Override
return true;
@Override
public Cursor query(Uri uri, String[] projec on, String selec on, String[] selec onArgs, String sortOrder) {
// Query the data (for this example, we just return a cursor with sample data)
return null; // return a cursor to the requested data (e.g., database query results)
@Override
}
@Override
public int update(Uri uri, ContentValues values, String selec on, String[] selec onArgs) {
@Override
public int delete(Uri uri, String selec on, String[] selec onArgs) {
// Delete data
@Override
return "vnd.android.cursor.dir/vnd.com.example.bookprovider.books";
You need to declare the content provider in the AndroidManifest.xml so that other applica ons can access it.
<applica on
android:label="Book Provider"
android:icon="@mipmap/ic_launcher">
<provider
android:name=".BookContentProvider"
android:authori es="com.example.bookprovider"
</applica on>
android:authori es: Defines the unique iden fier for the provider. It must be unique across all apps.
android:exported: Set this to true to make the provider accessible to other apps.
5. Accessing Data from a Content Provider
Other applica ons can access data from the content provider using the ContentResolver. This allows querying, inser ng, upda ng, and dele ng data.
do {
} while (cursor.moveToNext());
cursor.close();
Content providers use URIs to iden fy and access data. These URIs follow the format:
content://<authority>/<path>
For example:
If you want to restrict access to your content provider, you can define permissions in the manifest:
<provider
android:name=".BookContentProvider"
android:authori es="com.example.bookprovider"
android:permission="com.example.bookprovider.PERMISSION_READ"
android:exported="true" />
<permission
android:name="com.example.bookprovider.PERMISSION_READ"
This allows you to enforce permission-based access to your content provider, making sure only authorized apps can access the data.
1. Secure Data Access: Always check for permissions before allowing data access, especially when sharing sensi ve informa on.
2. Export Data Wisely: Only export the content providers that need to be shared. If possible, limit the data that can be accessed by other apps.
3. Return Appropriate Data Types: Ensure that the getType() method returns correct MIME types for each data URI.
4. Op mize Performance: Use efficient querying methods (e.g., rawQuery(), query()) to ensure your content provider handles data efficiently.
Conclusion
Content providers are powerful tools in Android for sharing data securely between applica ons. By following the steps outlined, you can create and use content
Android provides several networking APIs that allow you to connect your applica on to the
internet, fetch data from remote servers, and interact with web services. The most common tasks
for networking in Android are sending HTTP requests, receiving HTTP responses, parsing the
response, and handling connec vity issues.
Here’s an overview of the various networking APIs and how to use them in Android:
H pURLConnec on: The standard HTTP client for making network requests.
Retrofit: A type-safe HTTP client for Android used for interac ng with REST APIs.
Volley: A high-level networking library for Android to handle networking tasks like requests,
responses, and caching.
WebSocket: For real- me communica on, WebSockets provide a persistent connec on.
H pURLConnec on is Android’s built-in HTTP client, used for making synchronous and
asynchronous HTTP requests. Here is an example of how to use H pURLConnec on to fetch data
from a server.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class NetworkTask extends AsyncTask<Void, Void, String> {
@Override
try {
// Define URL
connec on.setRequestMethod("GET");
connec on.setConnectTimeout(15000);
connec on.setReadTimeout(15000);
String line;
response.append(line);
}
result = response.toString();
} else {
connec on.disconnect();
} catch (Excep on e) {
e.printStackTrace();
return result;
@Override
super.onPostExecute(result);
Explana on:
o The H pURLConnec on is configured with a URL and method (GET in this case).
o We then read the response from the input stream and return it as a string.
o Finally, onPostExecute() is used to update the UI thread with the result.
OkH p is a popular HTTP client library for Android, offering more features and be er performance
than H pURLConnec on. It simplifies request execu on and handles many networking tasks
automa cally, such as connec on pooling and response caching.
2. Code Example
// Create request
.url("h ps://api.example.com/data")
.build();
@Override
// Handle failure
@Override
if (response.isSuccessful()) {
} else {
});
Explana on:
o The OkH pClient is created, and a Request object is built with the desired URL.
Retrofit is a type-safe HTTP client for Android, designed for easy integra on with REST APIs. It
abstracts the complexi es of networking and response parsing.
implementa on 'com.squareup.retrofit2:retrofit:2.9.0'
implementa on 'com.squareup.retrofit2:converter-gson:2.9.0'
import retrofit2.Call;
@GET("data")
Call<List<DataModel>> getData();
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
call.enqueue(new retrofit2.Callback<List<DataModel>>() {
@Override
if (response.isSuccessful()) {
} else {
@Override
public void onFailure(Call<List<DataModel>> call, Throwable t) {
});
Explana on:
o Retrofit abstracts the networking details, so you define a simple interface (ApiService)
o Retrofit is ini alized with a baseUrl and a converter for parsing JSON responses (using
Gson here).
Volley is a powerful networking library developed by Google for handling network opera ons like
implementa on 'com.android.volley:volley:1.2.1'
2. Code Example
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class VolleyExample {
new Response.Listener<String>() {
@Override
// Handle response
},
new Response.ErrorListener() {
@Override
// Handle error
});
Explana on:
o StringRequest is used for making a GET request to a URL and receiving a string
response.
Use HTTPS: Always use HTTPS (SSL/TLS) for secure communica on.
Handle Network Failures Gracefully: Implement proper error handling for network meouts,
unavailable services, and other issues.
Caching: Cache network responses for be er performance and offline capabili es (supported
by libraries like Retrofit and OkH p).
Use Retry Logic: Implement retry strategies for failed network requests.
Conclusion
Android provides various networking APIs such as H pURLConnec on, OkH p, Retrofit, and Volley
for making network requests. Depending on your use case, you can choose the most appropriate
API. Retrofit and OkH p are popular for their simplicity and performance, while Volley is useful for
used method for deploying Android apps is through the Google Play Store. However, there are other op ons for distribu ng your app, such as using
Before you can deploy your Android app, you need to ensure that it is ready for release. This involves:
Android requires that your app be signed with a private key before it can be deployed. This ensures the app’s authen city and that it has not been
tampered with.
1. Open Android Studio and ensure your app is ready for release.
o Choose either an APK or an Android App Bundle (recommended for distribu on via Google Play).
o Enter the details for the key (such as key alias, password, and validity).
Google Play now recommends distribu ng apps using the Android App Bundle (.aab) format instead of APKs. App Bundles allow Google Play to
generate APKs op mized for different device configura ons, reducing the app's download size for users.
Before deploying, it’s crucial to thoroughly test your app to ensure it func ons correctly on various devices. This includes:
Tes ng on mul ple devices: Test your app on different screen sizes, resolu ons, and Android versions.
Using Android Emulator: Simulate different devices in Android Studio's Emulator for compa bility.
Beta Tes ng: Use pla orms like Google Play Console's internal tes ng or external testers via Firebase App Distribu on to get feedback before
making it public.
o Visit the Google Play Console and sign in with your Google account.
2. Agree to the Developer Distribu on Agreement: Make sure to read and agree to the terms and condi ons.
3. Set Up Your Account: Add necessary details such as your developer name, contact informa on, and country.
To publish your app, you need to fill out a detailed store lis ng. This includes:
Descrip on: Provide a detailed descrip on of the app’s features and func onality.
Screenshots: Add screenshots to showcase your app's interface and key features. You’ll need screenshots for different device types (phone,
tablet, etc.).
App Category: Choose an appropriate category (e.g., Games, Educa on, Health).
App Icon: Provide a high-quality app icon that will represent your app on the Play Store.
Privacy Policy URL: If your app collects personal data, include a link to your privacy policy.
1. Go to the Google Play Console and navigate to All Apps > Create Applica on.
5. Add a version name and version code (increment the version code with each new release).
You can set your app as Free or Paid. Google Play allows you to choose specific countries or regions where the app will be available.
If you’re crea ng a paid app, make sure you link your Google Wallet account for payments.
1. Click on Review and Rollout to launch your app to the Google Play Store.
2. Your app will go through a review process by Google, which can take a few hours to a few days. Google will check for policy viola ons, app
3. A er the review, your app will be available for download on the Google Play Store.
Once your app is live on Google Play, you’ll need to maintain and update it regularly. This can include fixing bugs, adding new features, and
Push Updates: You can release updates by genera ng new signed APKs/App Bundles and uploading them to the Google Play Console.
Versioning: Increment your app version code with each update to differen ate the versions.
Release Channels: You can use closed tes ng or open beta tracks to test new versions before releasing them to produc on.
While Google Play is the primary distribu on method, you can also distribute your app in other ways:
There are other app stores where you can distribute your Android app:
Samsung Galaxy Store: For devices that run Samsung’s opera ng system.
You can distribute the APK directly to users, but this method has limita ons:
Users need to manually enable installa on from "Unknown Sources" in their device se ngs.
You won’t have access to app analy cs or the Play Store’s wide reach.
Once your app is published, you can monitor its performance, user acquisi on, and user feedback:
Google Play Console: Provides insights into app performance, user ra ngs, crash reports, and more.
Firebase Analy cs: Use Firebase Analy cs to track user behavior and app usage.
Crashly cs: Firebase’s tool for real- me crash repor ng to iden fy issues in your app.
User Reviews: Respond to user feedback and ra ngs on the Play Store to improve your app’s reputa on.
To ensure that your app reaches a wide audience, you may need to market it:
App Store Op miza on (ASO): Op mize your app’s tle, descrip on, and keywords to improve visibility on the Play Store.
Social Media: Use pla orms like Facebook, Twi er, Instagram, and TikTok to promote your app.
Paid Ads: Consider using Google Ads, Facebook Ads, or other ad networks to promote your app.
Influencer Partnerships: Collaborate with influencers to review and promote your app.
Conclusion
Deploying an Android applica on to the world involves preparing the app for release, genera ng a signed APK or App Bundle, se ng up a Google
Play Developer account, publishing the app to the Play Store, and managing it a er launch. Regular updates and user feedback are essen al for the
app's long-term success. By following the steps above and marke ng your app effec vely, you can reach a global audience and ensure your app's