[JAVA] I want you to use Enum # name () for the Key of SharedPreference

Note: I am exhausted in the middle of my ambition

SharedPreference is good!

The standard API SharedPreference is nice! It depends on the scale of the application, but it is very reliable when you like "DB and messed up !!!!!!". Since the primitive type is suppressed, small flags can be saved. Even if I update the app, it's crap. Since it is saved in xml, you can easily see the contents. You did it!

Severe reality

Here is an app that manages settings with SharedPreference. The number of keys is over 100. Keys are scattered all over the place, such as being written in a constant class, being made a constant in Activity, or being written directly.

sharedPreference.getAll.toString()

If you manage to look inside the Shared Preference, you will close it. From now on you have to grep the keys one by one, pick them up and decipher the meaning of the keys and values. It's hard.

A list of the harsh realities I've seen

--Overwrite an existing key that you don't even know where it is inadvertently --I don't know how to retrieve the value I want because the key is dynamically generated. --The same value is saved three times with different keys --There is a SharedPrefUtil class for each screen (and stored in the same SharedPreference) --As a result of typoing the key name, only the default value is included at any time.

Cause

I think most of the problems caused by SharedPreference are due to key management. Even if you put them together as a constant class, if multiple people edit it, you may inadvertently define the same key as the existing one. It's a pain to have to go to the places I use to check the value type for that key.

so

As the title of the article. I want you to use ʻEnum.name () `.

Not scattered

All the keys are defined in the same enum class. You can see at a glance which key is defined.

Keys never duplicate

If the definition name is covered, it will not compile in the first place, so you can rest assured.

Safe to manage keys separately

If you create an enum class for each group of keys, the keys will not be mixed and messed up.

By the way, ʻEnum.name () instead of ʻEnum.toString () is because @Override cannot be done. It's quite possible that someone kind will override toString and explain what's inside.

Tried to make it

I personally wish I could do this! The enum for Shared Preference is as follows.

FoodPref.java


import android.content.Context;
import android.content.SharedPreferences;

enum FoodPref {
    //Octopus
    TAKO(100),
    //Cat
    NEKO(200),
    //There
    SOKO(300);

    //Default value.
    public final Object DEF;

    FoodPref(Object def) {
        this.DEF = def;
    }

    //Shared Preference for this enum only
    public static SharedPreferences getThisPreference(final Context context) {
        return context.getSharedPreferences(FoodPref.class.getSimpleName(), Context.MODE_PRIVATE);
    }
}

How to use


        //Create
        SharedPreferences foodSp = FoodPref.getThisPreference(context);
        //Put out
        int cat = foodSp.getInt(FoodPref.NEKO.name(), (Integer) FoodPref.NEKO.DEF);
        //Put in
        foodSp.edit().putInt(FoodPref.SOKO.name(), 666).apply();


        //Even if it increases in various ways
        SharedPreferences toySp = ToyPref.getThisPreference(context);
        //Because it is saved separately
        SharedPreferences carSp = CarPref.getThisPreference(context);
        //There is no risk of mixing values
        SharedPreferences bookSp = BookPref.getThisPreference(context);

Remaining challenges

Conclusion

I'd be happy if someone could do something better!

Recommended Posts

I want you to use Enum # name () for the Key of SharedPreference
I want to display the name of the poster of the comment
I want you to use Scala as Better Java for the time being
The story of Collectors.groupingBy that I want to keep for posterity
I want to output the day of the week
I want to display the number of orders for today using datetime.
eclipse I definitely want you to use Transcendental Recommended Shortcut Key (Windows)
I want to var_dump the contents of the intent
When you want to use the method outside
[Ruby] I want to extract only the value of the hash and only the key
[Rails + Webpacker] I want to use images of assets! Until you can view the image in Vue.js
I want to know the answer of the rock-paper-scissors app
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
For those who want to use MySQL for the database in the environment construction of Rails6 ~.
[Beginner] I want to modify the migration file-How to use rollback-
I want to use screen sharing on the login screen on Ubuntu 18
I want to expand the clickable part of the link_to method
I want to change the log output settings of UtilLoggingJdbcLogger
I want to use the sanitize method other than View.
I want to give a class name to the select attribute
When you want to change the MySQL password of docker-compose
I want to return multiple return values for the input argument
[Ruby] I want to reverse the order of the hash table
I want to temporarily disable the swipe gesture of UIPageViewController
I want to use FormObject well
I want to create a chat screen for the Swift chat app!
I want to limit the input by narrowing the range of numbers
[Java] I want to perform distinct with the key in the object
I want to control the default error message of Spring Boot
I want to change the value of Attribute in Selenium of Ruby
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
I want to use DBViewer with Eclipse 2018-12! !!
I want to use @Autowired in Servlet
A memo when you want to clear the time part of the calendar
Glassfish tuning list that I want to keep for the time being
I want to know the JSP of the open portlet when developing Liferay
I tried to summarize the key points of gRPC design and development
I want to pass the argument of Annotation and the argument of the calling method to aspect
I tried to make full use of the CPU core in Ruby
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
If you want to satisfy the test coverage of private methods in JUnit
[RxSwift] I want to deepen my understanding by following the definition of Observable
I want to get the value of Cell transparently regardless of CellType (Apache POI)
I want to control the start / stop of servers and databases with Alexa
I want to use arrow notation in Ruby
You may not want to use the remove method in ArrayList very often
I want to use java8 forEach with index
I want to get a list of only unique character strings by excluding fixed character strings from the file name
Output of how to use the slice method
How to use enum (introduction of Japanese notation)
[Eclipse] I want to use the completion function, but I want to manage to confirm the completion with spaces.
I want to truncate after the decimal point
I want to separate the handling of call results according to the API caller (call trigger)
Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement
I want to see the contents of Request without saying four or five
I want to recursively get the superclass and interface of a certain class
I want to get the value in Ruby
I want you to put the story that the error was solved when you stabbed the charger in the corner of your head
[Ruby] I want to make a program that displays today's day of the week!
Rails The concept of view componentization of Rails that I want to convey to those who want to quit