Android: Working with Preferences and Settings

In this article I go over using the built-in Android settings and preference system. I have a settings class as well as an activity that manages user input. A spinner is assigned the task of letting the user turn on or off a vibration feature. When the application is started again, the setting is accessed and assigned to the spinner. It also enables or disables the vibrator based on our saved preference.

The code is available on GitHub here.

https://www.youtube.com/watch?v=8h88t7sJC2o


Here is our Settings class:


public class Settings {
    public static final String PREFS_NAME = "twoc_settings_example";
    public static final String KEY_SETTINGS_AVAILABLE = "settingsavailable";
    // your custom settings in the application
    public static final String KEY_STATE_VIBRATION = "vibrationstate";

    // the object used to access settings for this application stored in a predefined setting area
    SharedPreferences prefAccessor;

    public Settings(Context parentContext) {
        prefAccessor = parentContext.getSharedPreferences(PREFS_NAME, 0);

        // this code should execute only once when the application is first executed once installed
        if (!prefAccessor.contains(KEY_SETTINGS_AVAILABLE)) {
            SharedPreferences.Editor editor = prefAccessor.edit();

            // make it so that we won't need to run this initialization code again
            editor.putString(KEY_SETTINGS_AVAILABLE, "true");

            // make sure preferences exist, if they don't initialize them with defaults
            if (!prefAccessor.contains(KEY_STATE_VIBRATION)) {
                editor.putString(KEY_STATE_VIBRATION, "On");
            }

            editor.apply();
        }
    }

    /**
     * return an application setting
     * use the public static KEY_.... constants of this class as the function parameter
     *
     * @param settingKeyName key name from one of the internal constants
     * @return the value or an empty string if not found
     */
    public String getSettingValue(String settingKeyName) {
        return prefAccessor.getString(settingKeyName, "");
    }

    /**
     * set one of the application settings
     * use the public static KEY_.... constants of this class
     * as the function parameter (settingKeyName)
     *
     * @param settingKeyName key name from one of the internal constants
     * @param valueToInsert value to save into that setting
     */
    public void setSettingValue(String settingKeyName, String valueToInsert) {
        SharedPreferences.Editor editor = prefAccessor.edit();
        editor.putString(settingKeyName, valueToInsert);
        editor.apply();
    }

    /**
     * a function to quickly get the vibration setting value
     *
     * @return the setting value
     */
    public boolean isVibrationOn() {
        return prefAccessor.getString(KEY_STATE_VIBRATION, "").equals("On");
    }
}

In there we deal with the first-run initialization of the preferences for our application and any defaults we want to define. I also have two generalized functions that allow you to save or get a setting. There is a function that allows us quick access to the vibrator on/off setting that we use in the Activity.

Here is our main activity:


import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;

public class MainActivity extends Activity {
    Resources resourcePointer;
    Settings settings;
    String[] arrayOnOff;
    Spinner vibrationSpinner;
    Button quitButton;
    Activity thisActivity;
    Vibrator vibrator;
    boolean vibrationOn = true;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        thisActivity = this;

        // instantiate our custom settings object
        settings = new Settings(this);

        // initialize a variable that we can use to access project resources
        resourcePointer = getResources();

        // fetch needed array lists for the options controls
        arrayOnOff = resourcePointer.getStringArray(R.array.array_onoff);

        vibrationSpinner = findViewById(R.id.options_vibration_spinner);
        vibrationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {}

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                settings.setSettingValue(Settings.KEY_STATE_VIBRATION, arrayOnOff[position]);
                vibrationOn = settings.isVibrationOn();
            }
        });

        // create a handler for the quit button
        quitButton = findViewById(R.id.main_btn_quit);
        quitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                thisActivity.finish();
            }
        });
    }

    /*** this happens after onCreate and after a restart */
    @Override
    public void onStart() {
        super.onStart();

        // attempt to select a previously saved setting if needed
        String currentVibrationSetting = settings.getSettingValue(Settings.KEY_STATE_VIBRATION);
        if (!currentVibrationSetting.trim().equals("")) {
            int spinnerPosition = getSpinnerItemPosition(vibrationSpinner, currentVibrationSetting);
            if (spinnerPosition > -1) {
                vibrationSpinner.setSelection(spinnerPosition);
            }
        }

        // initialize the vibrator service if necessary
        vibrationOn = settings.isVibrationOn();
        if (vibrationOn) {
            // use the vibration feature of the device if desired by the user
            vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        }
    }

    /*** attempt to find an item in a spinner based on the textual value */
    int getSpinnerItemPosition(Spinner spinner, String stringToFind) {
        int index = -1;
        for (int i = 0; i < spinner.getCount(); i++) {
            if (spinner.getItemAtPosition(i).equals(stringToFind)) {
                index = i;
                break;
            }
        }
        return index;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (vibrationOn && vibrator != null) {
                    vibrator.vibrate(100);
                } else if (vibrationOn) {
                    // (re)initialize the vibrator object
                    vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                    vibrator.vibrate(100);
                }
                break;
        }
        return true;
    }
}

In this case we deal setting up the user interface, handing the setting being changed, and managing the vibrator based on that setting.