Data Handling in Android

  1. Temporary Storage
  2. Shared Preferences
  3. Files
  4. SQLiteDatabase

Data Storage Overview

  1. Activity life cycle is not under your control
  2. Activity can be removed when its no longer on the screen
  3. Change in Screen Rotation causes Activity to restart

Activity State

Storing Temporary Application State

  • onSaveInstanceState
  • onRestoreInstanceState

Saving and Retrieving Instance State

public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("loaded", true);
        outState.putString("sortByChoice", sortByChoice);
        super.onSaveInstanceState(outState);
}

Loading data 

Saving Data

public void onActivityCreated(Bundle outState) {
       int nextPage = savedInstanceState.getInt("nextPage");
       super.onActivityCreated(outState);
}

Shared Preferences

  • Share small amounts of data 
  • Preferences have names
  • Can be public or private

Shared Preferences

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
String sorting = prefs.getString("testPref","defaultValue");

Loading data from Preferences

Writing to Preferences

 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
 SharedPreferences.Editor spe = sp.edit();
 spe.putInt("testPref", "helloworld");
 spe.apply();

SQLite Database

  • Support for SQLite db
  • Database is private to the app
  • SQLiteOpenHelper , a wrapper for db actions 

Data Sharing and Retrieval

  1. Content Providers
  2. Content Resolvers

Content Providers

  1. Sharing data across Apps
  2. Generic Interface of Data 
  3. Permission Control
  4. Native Db available as content providers

Content Resolver

  1. Application context has content resolver
  2. Uniform way to access resources using URI
CONTENT_URI= "content://com.example.project.healthcareprovider/nurses/rn"
Cursor c = getActivity().getContentResolver().query(CONTENT_URI,null, "movie_id =?",new String[]{movie.getId()+""},sortOrder);

Data Handling in Android

By Abhik Mitra

Data Handling in Android

  • 1,279