Skip to main content

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.

Popular posts from this blog

ChatGPT is a new, and faster, way to do programming!

Currently ChatGPT is in a free “initial research preview” . One of its well known use cases at this point is generating software code. I’ve also just used it to write most of this article… Well, actually a future article about cleaning up SRT subtitle files of their metadata faster than I have been by hand with Notepad++ and its replace functionality. Update: I recorded a screencast of writing the SRT subtitle cleaner application loading and processing portion. I relied heavily on ChatGPT for code. It was a fun process! https://youtu.be/TkEW39OloUA ChatGPT, developed by OpenAI, is a powerful language model that can assist developers in a variety of tasks, including natural language processing and text generation. One such task that ChatGPT can help with is creating an SRT cleaner program. SRT, or SubRip Subtitle, files are commonly used to add subtitles to video files. However, these files can become cluttered with unnecessary information, such as timing lines or blank spaces. To clean...

Theme error in 2010s Android App after AppCompat Migration

I plan on releasing a lot of my old work as GPL open source, but most of it has aged to the point that it no longer functions, or if it does work it’s running in compatibility mode. Basically it’s no longer best practices. Not a good way to start off any new public GPL projects, in my opinion. The current project I’m working on is an Android app that calculates star trails meant to help photographers get or avoid that in their night time photos. For now I’m going to skip some of the import process because I didn’t document it exactly. It’s been mostly trial and error as I poke around Android Studio post import. The Android Studio import process… Removing Admob Google Play code before the project would run at all. After removing dependencies, it kind of worked, but when running it in the emulator it shows a pop-up message saying that the app was developed for an old version of Android. Going through the process of updating code to match current best practices… I had the IDE convert the ...

Printing to file in Linux WINE

I noticed that this post has been sitting as a draft since 2011. At this point I have no idea if it’s useful or what I was even doing, but I might as well make it public in case someone can find it helpful! So I’ve been trying to get one of those PDF print drivers working in WINE without success. I then came upon a process that might work. When printing you need to select the checkbox “Print to file” that creates a .prn file. Just Linux things... I was using a program that only has printing facilities, but I want to export around 100 pages of text and images. Once you have the .prn (postscript) file, you can do any number of things to it. In my case I want the postscript file to be converted to HTML. I am also considering PDF format because that has more conversion options to eventually get me to HTML or plain text. sudo apt-get install cups-pdf Or it looks like that package might have changed to this… sudo apt-get install printer-driver-cups-pdf Where PDFs would be generated in /home/...