Basics of Data Saving and Storage System Using Android Studio 1.0

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 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 aa 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 preferences

 
However, using the builtin library classes and methods we can create a new shared preference as in the following:
  • getSharedPreferences()- Use this if you need multiple shared preference files identified by a 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 the name of the resource string R.sring.preference_file_key. Note that private mode for opening this file could be a better option.
  1. Context context = getActivity();     
  2. SharedPreferences sharedPref = context.getSharedPreferences(     
  3. 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:
  1. 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 shared preferences.
  • 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
  1. SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);     
  2. SharedPreferences.Editor editor = sharedPref.edit();     
  3. editor.putInt(getString(R.string.saved_high_score), newHighScore);     
  4. editor.commit();  

Read from Shared Preferences

 
To 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:
  1. SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);     
  2. int defaultValue = getResources().getInteger(R.string.saved_high_score_default);     
  3. long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);    

Saving Files

 
Saving 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 a 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 Storage

 
All 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 storage
 
It's not always available, because it depends upon the user to buy an external storage source when they need 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 application's 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:
  1. <manifest ...>     
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />     
  3. ...     
  4. </manifest>   
For reading
  1. <manifest ...>     
  2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />     
  3. ...     
  4. </manifest>    

    Saving a file on Internal Storage

     
    For storing the data in the form of a file then choose the appropriate directory and use the following methods:
    • getFilesDir()
    Return a File representing an internal directory for the application:
    • getCacheDir()
    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
    1. 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.
    1. String filename = "myfile";     
    2. String string = "Hello world!";     
    3. FileOutputStream outputStream;     
    4.     
    5. try {     
    6.    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);     
    7.    outputStream.write(string.getBytes());     
    8.    outputStream.close();     
    9. catch (Exception e) {     
    10.    e.printStackTrace();     
    11. }    
      Saving a file on External Storage
       
      This is the same as in the preceding code but a little different because the storage is external, in other words on SD cards.
      1. /* Checks if external storage is available for read and write */     
      2.     
      3. public boolean isExternalStorageWritable() {     
      4.    String state = Environment.getExternalStorageState();     
      5.    if (Environment.MEDIA_MOUNTED.equals(state)) {     
      6.    return true;     
      7. }     
      8.    return false;     
      9. }     
      10.     
      11. /* Checks if external storage is available to at least read */     
      12.     
      13. public boolean isExternalStorageReadable() {     
      14.    String state = Environment.getExternalStorageState();     
      15.    if (Environment.MEDIA_MOUNTED.equals(state) ||     
      16.       Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {     
      17.       return true;     
      18. }     
      19.       return false;     
      20. }    
      Deleting a File
      1. myFile.delete();    
      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();
       

      Summary

       
      This 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. 


      Similar Articles