Edited 2 weeks ago by ExtremeHow Editorial Team
AndroidData SavingConnectivityOptimizationSettingsSmartphonesTipsMobile DevicesData ManagementUser Interface
This content is available in 7 different language
Saving data on an Android device is an essential part of mobile application development. This document will provide you with a comprehensive understanding of the various methods used to save data on an Android device. There are many ways to save data, including shared preferences, internal storage, external storage, SQLite databases, and more.
Before getting into the specifics of each storage method, it's important to understand the general principles that guide data storage in Android. You need to consider factors such as the type of data you're saving, the required consistency of this data, and the privacy of the data. Let's first outline the main data storage options you have on Android:
Shared Preferences is suitable for storing small amounts of data in the form of key-value pairs. It is often used to save user settings or application preferences. Here is how you can use SharedPreferences in your Android application:
You can get a SharedPreferences instance by calling getSharedPreferences()
method, which requires two parameters: the name of the preferences file and the mode.
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
To save data in SharedPreferences, you need to use SharedPreferences.Editor
object. Here's a quick way to do this:
SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("username", "john_doe"); editor.putInt("user_id", 12345); editor.apply();
Getting data from shared preferences is simple. You can use getX()
methods, where X is the data type you want to get:
String username = sharedPreferences.getString("username", "default_name"); int userId = sharedPreferences.getInt("user_id", 0);
Internal storage is used to save files that only your application can access. It is best suited for private data. Here is how you can work with internal storage:
You can write to a file using the FileOutputStream
class. Here is an example of writing a simple text file:
String filename = "myfile.txt"; String fileContents = "Hello World!"; FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); fos.write(fileContents.getBytes()); fos.close();
To read a file from internal storage you need to use FileInputStream
:
FileInputStream fis = openFileInput(filename); InputStreamReader inputStreamReader = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } String fileContents = sb.toString();
External storage can be a removable media such as an SD card or a portion of the device's memory that is accessible to the user. This is useful for large files or files that can be shared across applications. Here's how you can use external storage:
Before using external storage, make sure your AndroidManifest.xml file includes the required permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To write data to external storage, use File
class to define a directory and file path:
File externalStorageDir = Environment.getExternalStorageDirectory(); File myFile = new File(externalStorageDir, "myfile.txt"); FileOutputStream fos = new FileOutputStream(myFile); fos.write("Hello World!".getBytes()); fos.close();
Reading a file from external storage can be accomplished using FileInputStream
:
FileInputStream fis = new FileInputStream(myFile); InputStreamReader inputStreamReader = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } String fileContents = sb.toString();
SQLite is a powerful storage option for structured data and provides a complete SQL database for storing data. It is perfect for large or complex data structures. Let's learn how to create and use a SQLite database in Android:
You need to create a helper class that extends SQLiteOpenHelper
to manage database creation and version management:
public class MyDbHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "mydatabase.db"; public MyDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS users"); onCreate(db); } }
You can do data entry using ContentValues
:
MyDbHelper dbHelper = new MyDbHelper(getContext()); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", "John Doe"); values.put("age", 29); long newRowId = db.insert("users", null, values);
Querying data is done using query()
or rawQuery()
method:
SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query("users", new String[] {"id", "name", "age"}, null, null, null, null, null ); while(cursor.moveToNext()) { long userId = cursor.getLong(cursor.getColumnIndexOrThrow("id")); String userName = cursor.getString(cursor.getColumnIndexOrThrow("name")); int userAge = cursor.getInt(cursor.getColumnIndexOrThrow("age")); } cursor.close();
Room is an abstraction layer over SQLite that simplifies database access, allowing you to write your queries in the Fluent API or rely on compile-time SQL diagnostics. Here are the basic steps:
Define an entity for the table representation using the @Entity
annotation:
@Entity public class User { @PrimaryKey public int id; public String name; public int age; }
You define methods to access the database through the DAO:
@Dao public interface UserDao { @Insert void insertAll(User... users); @Query("SELECT * FROM user") List<User> getAll(); }
Create an abstract class that extends RoomDatabase
and contains the entities and DAOs:
@Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); }
You can use the database defined in your application as follows:
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build(); UserDao userDao = db.userDao(); List<User> users = userDao.getAll();
In conclusion, Android offers several methods for data storage, and you can choose from them based on your specific needs. Understanding the strengths and limitations of each method will guide you in making practical decisions during your app development.
If you find anything wrong with the article content, you can