Introduction
Consider the fact that when you are doing something on your Android phone and suddenly a call comes in. Then after the call will your work be lost? So in these cases when the onPause() method is called of an activity then it is the responsibility of the Android system to save the local data or local work the user is doing.
Some features are:
- Saving key-value pairs of simple data types in a shared preferences file.
- Saving arbitrary files in Android's file system.
- Using databases managed by SQLite.
Saving Key/Value Sets
If a user has a small collection of key/values that everyone would like to save then it is the programmer's duty to use good classes during development like the shared preferences APIs. A shared preference object always points to a file that contains key/value pairs and provides a simple method to read and write them.
Each and every value that is supposed to be a key and related objects are managed by the Android framework that could be private or shared.
An interface for accessing and modifying preferences data is returned by getsharedfreferences(String, int). For the specific set of preferences there is only one object or instance of this class to handle all the client's share.
Get a handle to a shared preferencesHowever using the builtin library classes and methods we can create a new shared preferences as in the following:
- getSharedPreferences(): Use this if you need multiple shared preference files identified by name that can be specified with the first parameter. We can call this from any Context in the application.
- getPreferences(): can be used from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, we don't need to provide a name.
It can be correlated with the fragments likewise if a code is executed inside a fragment. It could access the shared preferences files identified by name of the resource string R.sring.preference_file_key. Note that private mode for opening this file could be a better option.
- Context context = getActivity();
- SharedPreferences sharedPref = context.getSharedPreferences(
- getString(R.string.preference_file_key), Context.MODE_PRIVATE);
Naming conventions must be unique in the case of shared preferences. For example
"com.example.MyFirstApp.PREFERENCE_FILE_KEY". Alternatively it can be thought as instead of the preceding code we can use the
getpreference() method as in the following:
- SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
If we use
MODE_WORLD_READABLE and
MODE_WORLD_WRITEABLE then it could be accessible by the identifier by another application or eventually any other class.
Write to Shared Preferences
- To write to a shared preferences file, create a SharedPreferences.Editor by calling the edit() method on your sharedpreferences.
- the keys and values you want to write with methods such as putInt() and putString() immediately followed by commit() to save the changes.
For example:
- SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPref.edit();
- editor.putInt(getString(R.string.saved_high_score), newHighScore);
- editor.commit();
Read from Shared PreferencesTo retrieve values from a shared preferences file, we can use
getInt() and
getString(), providing the key for the value you want and optionally a default value to return if the key isn't present. For example:
- SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
- int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
- long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Saving FilesSaving the data and files in the Android device builtin repository is very similar to the disk-based data saving on other platforms. A File object is very convenient for reading or writing large amounts of data in start-to-finish (sequential) order without skipping the data. For example, it's good for image files or anything exchanged over a network.
Choosing Internal or External StorageAll Android devices provided by two types of storage named as internal or expandable storage that is ultimately a external source of storage. Historically most of the devices offered built-in non volatile memory called internal storage. Some of the devices divide the permanent storage space into "internal" and "external" partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not.
Internal storage
- It's always available.
- Files saved here are accessible by only your app by default.
- When the user uninstalls your app, the system removes all your app's files from internal storage.
Note: Internal storage is the best when the developer is sure that neither the user nor another application can access these files.
External storageIt's not always available, because it depends upon the user to buy an external storage source when they need of it. It's world-readable, so files saved here may be read outside of your control. When the user uninstalls an application, the system removes your applications files from here only if you save them in the directory from
getExternalFilesDir().
Obtaining Permissions for External Storage
To write to the external storage, we must counter write the WRITE_EXTERNAL_STORAGE permission in the manifest file:
- <manifest ...>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- ...
- </manifest>
For reading
- <manifest ...>
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- ...
- </manifest>
Saving a file on Internal StorageFor storing the data in the form of a file then choose the appropriate directory and use the following methods:
Return a File representing an internal directory for the application:
Returns a File representing an internal directory for the application temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it might show unused behavior and also delete your cache files without warning.
To create a file
- File file = new File(context.getFilesDir(), filename);
Alternatively we can
useopenFileOutput() to get a
FileOutputStream. Let us see how to write data to the file.
- String filename = "myfile";
- String string = "Hello world!";
- FileOutputStream outputStream;
-
- try {
- outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
- outputStream.write(string.getBytes());
- outputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
Saving a file on External StorageThis is the same as in the preceding code but a little different because the storage is external, in other words on SD cards.
-
-
- public boolean isExternalStorageWritable() {
- String state = Environment.getExternalStorageState();
- if (Environment.MEDIA_MOUNTED.equals(state)) {
- return true;
- }
- return false;
- }
-
-
-
- public boolean isExternalStorageReadable() {
- String state = Environment.getExternalStorageState();
- if (Environment.MEDIA_MOUNTED.equals(state) ||
- Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
- return true;
- }
- return false;
- }
Deleting a File
This preceding written method id is used to delete a file. If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling
deleteFile();SummaryThis article explained some basics of the File Storage in Android and the operations done on them using both mechanisms as said previously. We saw methods and classes used to save, read and write the file.