In mobile app development, handling data is a crucial task. This includes persisting data (saving it locally on the device) for future use and sharing data between apps or with external services. Both are important for creating efficient and user-friendly apps.
Let’s break down the key concepts and methods for persisting and sharing data in mobile apps.
Persisting data means saving data in such a way that it can be accessed later, even after the app is closed or the device is restarted. Mobile platforms provide several ways to store data locally.
For simple key-value pairs (e.g., settings or user preferences), Android provides SharedPreferences. This is ideal for storing small amounts of data like user preferences, app settings, or simple flags.
Saving Data:
SharedPreferences sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.putBoolean("isLoggedIn", true);
editor.apply(); // Apply changes asynchronously
Retrieving Data:
SharedPreferences sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "defaultName");
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
Use Case: SharedPreferences is suitable for storing small, non-sensitive data (e.g., user settings, preferences, and flags).
For more complex or structured data (e.g., records or lists), Android provides SQLite, a lightweight relational database. You can use it to store larger amounts of data locally.
Creating a Database and Table:
SQLiteDatabase db = openOrCreateDatabase("app_database", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);");
Inserting Data:
ContentValues contentValues = new ContentValues();
contentValues.put("name", "John Doe");
contentValues.put("age", 30);
db.insert("users", null, contentValues);
Retrieving Data:
Cursor cursor = db.query("users", new String[] {"id", "name", "age"}, null, null, null, null, null);
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
}
cursor.close();
Use Case: SQLite is ideal for storing structured, relational data such as user records, product lists, or transactions.
Both Android and iOS allow you to save data as files (text files, JSON, etc.). This is useful for larger datasets or for specific file types.
Writing to a File (Android):
FileOutputStream fos = openFileOutput("user_data.txt", MODE_PRIVATE);
fos.write("User data example".getBytes());
fos.close();
Reading from a File (Android):
FileInputStream fis = openFileInput("user_data.txt");
int character;
StringBuilder stringBuilder = new StringBuilder();
while ((character = fis.read()) != -1) {
stringBuilder.append((char) character);
}
fis.close();
Use Case: This is suitable when you need to store larger chunks of data, like user-generated content or log files.
For iOS, Core Data is a powerful framework for data persistence. It provides a high-level object graph management and persistence framework, which is ideal for storing complex data models.
Creating a Managed Object Context:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
Saving Data:
let newUser = User(context: context)
newUser.name = "John Doe"
newUser.age = 30
try? context.save()
Fetching Data:
let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
let users = try? context.fetch(fetchRequest)
Use Case: Core Data is best for complex data models, relationships between objects, and when you need features like undo/redo, versioning, and data migrations.
Sharing data allows your app to interact with other apps or services, or to share data between different parts of your own app. There are several ways to share data on both Android and iOS.
Both Android and iOS provide ways to share data with other apps.
Android (Using Intents to Share Data)
Android uses Intents to share data between applications. Intents can send data like text, images, or files to other apps. For example, sharing a text message via email:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out this message!");
startActivity(Intent.createChooser(sendIntent, "Share via"));
This will trigger an intent that allows the user to share the message via compatible apps, like email or social media.
iOS (Using UIActivityViewController to Share Data)
On iOS, UIActivityViewController is used for sharing content. It provides a standard interface for sharing data with other apps or services.
let textToShare = "Check out this cool message!"
let activityViewController = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
This opens a share sheet allowing users to share the content via supported apps.
You can also share data by integrating with external services like cloud storage (e.g., Google Drive, iCloud, Dropbox) or APIs.
Android (Using Retrofit or Volley for HTTP Requests)
Retrofit or Volley libraries allow Android apps to make HTTP requests to remote servers or APIs, where they can share or retrieve data.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<Response> call = apiService.sendData(data);
call.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, Response<Response> response) {
// Handle the response
}
@Override
public void onFailure(Call<Response> call, Throwable t) {
// Handle failure
}
});
iOS (Using URLSession for API Calls)
In iOS, you can use URLSession to send data to external services.
let url = URL(string: "https://example.com/api/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSONEncoder().encode(data)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error: $$error)")
} else {
// Handle response data
}
}
task.resume()
Android provides Content Providers for sharing structured data between apps. A content provider acts as an interface for data sharing, enabling apps to access shared data in different formats.
For example, reading contacts from the Contacts Provider:
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
cursor.close();
}
Cloud storage services allow apps to store and sync data across multiple devices or users.
Persisting Data and Sharing Data are fundamental aspects of mobile app development, ensuring that user data is stored safely and can be shared seamlessly across apps and platforms. Here’s a quick recap:
Persisting Data:
Sharing Data:
Effective data management helps make apps more functional, interactive, and useful to the user, allowing them to store and share information across devices and services.
Open this section to load past papers