In this tutorial, I'll show you how to make use of all those storage options in your Android apps. I'll also help you understand how to pick the most appropriate storage option for your data.
![]() |
If you are looking for a quick way to store a few strings or numbers, you should consider using a preferences file. Android activities and services can use the getDefaultSharedPreferences() method of the PreferenceManager class to get a reference to a SharedPreferences object that can be used to both read from and write to the default preferences file.
- SharedPreferences myPreferences
- = PreferenceManager.getDefaultSharedPreferences(MyActivity.this);
- SharedPreferences.Editor myEditor = myPreferences.edit();
- myEditor.putString("NAME", "Alice");
- myEditor.putInt("AGE", 25);
- myEditor.putBoolean("SINGLE?", true);
- myEditor.commit();
- String name = myPreferences.getString("NAME", "unknown");
- int age = myPreferences.getInt("AGE", 0);
- boolean isSingle = myPreferences.getBoolean("SINGLE?", false);
Note that preferences files are limited to strings and primitive data types only. If you wish to store more complex data types or binary data, you must choose a different storage option.
2. Using an SQLite Database
Every Android app can create and make use of SQLite databases to store large amounts of structured data. As you might already know, SQLite is not only light-weight, but also very fast. If you have experience working with relational database management systems and are familiar with both SQL, which is short for Structured Query Language, and JDBC, which is short for Java Database Connectivity, this might be your preferred storage option.
To create a new SQLite database, or to open one that already exists, you can use the openOrCreateDatabase() method inside your activity or service. As its arguments, you must pass the name of your database and the mode in which you want to open it. The most used mode is MODE_PRIVATE, which makes sure that the database is accessible only to your application. For example, here's how you would open or create a database called my.db:
- SQLiteDatabase myDB =
- openOrCreateDatabase("my.db", MODE_PRIVATE, null);
- myDB.execSQL(
- "CREATE TABLE IF NOT EXISTS user (name VARCHAR(200), age INT, is_single INT)"
- );
Here are two ContentValues objects you can use with the user table:
- ContentValues row1 = new ContentValues();
- row1.put("name", "Alice");
- row1.put("age", 25);
- row1.put("is_single", 1);
- ContentValues row2 = new ContentValues();
- row2.put("name", "Bob");
- row2.put("age", 20);
- row2.put("is_single", 0);
Once your ContentValues objects are ready, you can pass them to the insert() method along with the name of the table.
- myDB.insert("user", null, row1);
- myDB.insert("user", null, row2);
- Cursor myCursor =
- myDB.rawQuery("select name, age, is_single from user", null);
To fetch the value of an individual column, you must use methods such as getString() and getInt(), which expect the index of the column. For example, here's how you would retrieve all the values you inserted in the user table:
- while(myCursor.moveToNext()) {
- String name = myCursor.getString(0);
- int age = myCursor.getInt(1);
- boolean isSingle = (myCursor.getInt(2)) == 1 ? true:false;
- }
- myCursor.close();
- myDB.close();
Every Android app has a private internal storage directory associated with it, in which the app can store text and binary files. Files inside this directory are not accessible to the user or to other apps installed on the user's device. They are also automatically removed when the user uninstalls the app.
Before you can use the internal storage directory, you must determine its location. In order to do so, you can call the ggetFilesDir() method, which is available in both activities and services.
- File internalStorageDir = getFilesDir();
- File alice = new File(internalStorageDir, "alice.csv");
- // Create file output stream
- fos = new FileOutputStream(alice);
- // Write a line to the file
- fos.write("Alice,25,1".getBytes());
- // Close the file output stream
- fos.close();
Because the internal storage capacity of Android devices is usually fixed, and often quite limited, several Android devices support external storage media such as removable micro-SD cards. I recommend that you use this storage option for large files, such as photos and videos.
Unlike internal storage, external storage might not always be available. Therefore, you must always check if it's mounted before using it. To do so, use the getExternalStorageState() method of the Environment class.
- if(Environment.getExternalStorageState()
- .equals(Environment.MEDIA_MOUNTED)) {
- // External storage is usable
- } else {
- // External storage is not usable
- // Try again later
- }
- File bob = new File(getExternalFilesDir(null), "bob.jpg");
For example, by passing the value Environment.DIRECTORY_PICTURES to the method, you can determine the path of the public directory in which you can store photos. Similarly, if you pass the value Environment.DIRECTORY_MOVIES to the method, you get the path of the public directory in which movies can be stored.
Here's how you would reference a file called bob.jpg in the public pictures directory:
- File bobInPictures = new File(
- Environment.getExternalStoragePublicDirectory(
- Environment.DIRECTORY_PICTURES),
- "bob.jpg"
- );
Conclusion
You now know how to make the most of the local storage options provided by the Android SDK. Regardless of the storage option you choose, read/write operations can be time-consuming if large amounts of data are involved. Therefore, to make sure that the main UI thread always stays responsive, you must consider running the operations in a different thread.
Written by Ashraff Hathibelagal
If you found this post interesting, please follow and support us.
Suggest for you:
The Complete Android & Java Course - Build 21 Android Apps
Android Application Programming - Build 20+ Android Apps
The Complete Android Developer Course: Beginner To Advanced!
Android: From Beginner to Paid Professional
The Complete Android Developer Course - Build 14 Apps
No comments:
Post a Comment