Working with Shared Preferences in PSLab App

This blog demonstrates how to work with Shared Preferences in an Android app. The blog includes a detailed explanation about what are the methods available to store data in Android and where to use Shared Preferences (a type of data storage method) to save extra memory usage and work efficiently. After the detailed explanation is a step by step guide on how to use Shared Preferences in any Android app by taking an example of one used in PSLab Android app under PR #1236

What are methods available in Android for data storage ?

Android provides a variety of methods to store data some of which are

  1. Shared Preferences
  2. Internal Storage
  3. External Storage
  4. SQLite Database

A very brief description of the above four data storage method would be

  • Shared Preference – Used to store key-data pair for a given app
  • Internal Storage – Used to store any type of data such as pictures, videos, etc. which can be used only within the app
  • External Storage – Used to store any type of data such as audio, video, etc. which can be shared between different apps or different systems
  • SQLite database – It is also a type of Internal Storage method but with a different programming language in use which is SQL

Where to use different data storage methods?

Following are some of the  distinct cases where the above-mentioned data storing methods can be differentiated

  • Shared Preference – Shared Preference should be used when a very small amount of data i.e. key-value pair data is to be stored. An example of it would be storing the state of a widget when an app is closed and restoring the state when the app is opened again.
  • Internal Storage – Internal storage should be used while storing data such as text files, audio, video, photographs, etc. but occupying a very less device memory space. So, internal storage should be used when a limited amount of data needs to be stored for app execution.
  • External Storage – External storage should be used when data to be stored is very large and as a result, Internal storage can’t be used. External Storage can also write data on external memories like SD Card, etc.

How to use Shared Preferences in an Android app?

Following is a step by step guide on how Shared Preferences were used in PSLab Android app

  • First, declare a variable using final and static keyword so as to make its value permanent because it will be used to differentiate current activity/fragment data from other activity/fragment data in a common folder of Shared Preference.
private static final String FRAG_CONFIG = "LuxMeterConfig";
  • Now, we can make Shared Preferences for current activity/fragment by using the code:

When in Activity:

final SharedPreferences settings = getSharedPreferences(FRAG_CONFIG, Context.MODE_PRIVATE);

When in fragment:

final SharedPreferences settings = getActivity().getSharedPreferences(FRAG_CONFIG, Context.MODE_PRIVATE);

Here Context.MODE_PRIVATE is a context through which we define our Shared Preference i.e. for the current context it means that the above made Shared Preference can only be used inside the current activity/fragment. A detailed description of other modes available can be found in [1].

  • Now, Shared Preference for current activity/fragment is ready for use and so now, we can add as many numbers of the key-value pair as we want by using the following code
settings.getInt("HighValue", 2000);

Here, “HighValue” is the key whereas 2000 is the value. The above method is used to give a default value when a pair is created.

  • Now to edit the value of any before-made pair, we can use the Editor method available in the Shared Preference class to edit the default value.
SharedPreferences.Editor editor = settings.edit();
editor.putInt("HighValue", 5000);
editor.apply();

Here, the editor is an instance of edit() method available in Shared Preference class. After changing the default value of the key, we can use apply() method to apply the changes to the default key-value pair.

Where to find the Shared Preference folder on the target device?

To find the Shared Preference folder for any Android application, do the following steps:

  • Connect the target device (device on which app is installed) to the system running Android Studio.
  • Now click on the “Device File Explorer” button in Android Studio as shown in figure 1.

Figure 1. Device File Explorer button in Android Studio

  • Now after clicking the button, a list of folders would pop up as shown in figure 2.

Figure 2. Screenshot of Android Studio showing list of folders on the device

  • Now follow the given path, and you can see the desired folder
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

So, in this way, the Shared Preferences can be used for data storage in any Android application.

Resources

  1. https://www.androidauthority.com/how-to-store-data-locally-in-android-app-717190/ – Documentation on different modes available to define the context of Shared Preference
  2. https://stackoverflow.com/questions/6146106/where-are-shared-preferences-stored – StackOverflow Q/A for where the Shared Preferences are stored on the target device
Continue ReadingWorking with Shared Preferences in PSLab App

Making custom dialog boxes in PSLab app

This blog covers the topic of how to create custom dialog boxes in an Android app by taking an example of how it was implemented in PSLab Android application. The custom dialog box that will be illustrated in this blog will have a layout similar to that from my PR feat: added a guide for Logic Analyzer Instrument using Alert Dialog Box in PSLab Android repository. But all the main functionalities that can be added to a custom dialog will be illustrated in this blog.

How custom dialog was implemented in the PSLab app?

  • The first step is to make a layout for the custom dialog box. The layout of custom dialog should be such that it shouldn’t occupy the whole screen as the idea here is to overlay the dialog over the activity and not replace the whole activity with the dialog layout. The layout can be implemented by using the following attributes :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

       <TextView
           android:id="@+id/custom_dialog_text"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"/>

       <ImageView
           android:id="@+id/custom_dialog_schematic"
           android:layout_width="wrap_content"
           android:layout_height="@dimen/schematic_height" />

       <TextView
           android:id="@+id/description_text"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" />

       <CheckBox
           android:id="@+id/toggle_show_again"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_below="@id/toggle_show_again">

           <Button
               android:id="@+id/dismiss_button"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content" />

       </RelativeLayout>
   </RelativeLayout>
</ScrollView>

The result of the above layout after adding proper margins and padding is as shown in figure 1.

Figure 1. The output of the layout made for custom dialog

  • Now as the layout is ready, we can focus on adding Java code to inflate the layout over a particular activity. Make a function in the activity or the fragment in which the custom dialog is to be inflated. Add the following code (if the layout is same as that in PSLab app else modify the code as per the layout) in the function to display the custom dialog box.
public void howToConnectDialog(String title, String intro, int iconID, String desc) {
   try {
       final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
       LayoutInflater inflater = getLayoutInflater();
       View dialogView = inflater.inflate(R.layout.custom_dialog_box, null);

 // Find and set all the attributes used in the layout and then create the dialog as shown
       
       builder.setView(dialogView);
       builder.setTitle(title);
       final AlertDialog dialog = builder.create();
       ok_button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
                dialog.dismiss();
           }
       });
       dialog.show();
   } catch (Exception e) {
       e.printStackTrace();
   }
}

Here, the LayoutInflater inflates the custom dialog layout in the Alertdialog builder. The Alertdialog builder is used to hold and set values for all the views present in the inflated layout. The builder then creates a final custom dialog when builder.create() method is called. Finally, the dialog is shown by calling method dialog.show() and is dismissed by calling method dialog.dismiss().

  • Now the dialog box is ready and it will be inflated when the above method is called. But the “Don’t show again” checkbox currently has no functionality and so the dialog box will pop up although “Don’t show again” checkbox is ticked mark by the user. For adding this functionality, we will need to use Shared Preferences to save the state of the dialog box. For using Shared Preferences, first, add the following lines of code in the above method
final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
Boolean skipMessage = settings.getBoolean("skipMessage", false);

The PREFS_NAME is the key to distinctly identify the state of the given dialog box from the stored state of many dialog boxes (if any). A suggested key name is “customDialogPreference”. The skipMessage is a boolean used here to check the state if the dialog box should be inflated or not.

Now format the onClickListener of the OK button with the following code :

Boolean checkBoxResult = false;
if (dontShowAgain.isChecked())
   checkBoxResult = true;
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("skipMessage", checkBoxResult);
editor.apply();
dialog.dismiss();

The following code checks the state of “Don’t show again” dialog and then inflates the custom dialog if applicable. If the checkbox is ticked mark then on pressing the OK button the dialog won’t be inflated again.

Resources

  1. https://developer.android.com/guide/topics/ui/dialogs – Android Documentation on Dialogs (Great Resource to make a custom dialog)
Continue ReadingMaking custom dialog boxes in PSLab app