Thursday, January 26, 2017

Remember Where Readers Left Off

Apps that allow users to read books need to remember where the reader left off the last time the book was read. In Android, this is very easy to do using SharedPreferences.

Because of the Android lifecycle, there are 3 places to deal with the previous location.

1. In the onPause() method, store the current URL in SharedPreferences using the name of the icon as a unique identifier.

@Override
protected void onPause()
{
    super.onPause();
    SharedPreferences sharedPref = getSharedPreferences(getString(R.string.osc_package),MODE_PRIVATE);
    SharedPreferences.Editor ed = sharedPref.edit();
    if(webView != null && content != null)
    {
        String url = webView.getUrl().replace("?bookmark=1", "");
        ed.putString(content.getIcon(), url);
        ed.apply();
    }
}

2. In onCreate(), SharedPreferences is checked for a previous URL. If one is available, it is used.

SharedPreferences sharedPref = getSharedPreferences(getString(R.string.osc_package), MODE_PRIVATE);
String url = sharedPref.getString(content.getIcon(), "");

3. In onResume(), SharedPreferences is checked for a previous URL. If one is available, it is used.

It is very simple solution that allows the reader to continue where they left off without creating a bookmark. The code is in the WebViewActivity class of the OpenStax app. The code is available on Github .