Best practices for storing translatable android strings in DB

575 views Asked by At

In one of my app's forms I have an spinner populated from an string array android resource, thus translation is managed creating additional XML files in the android app. The form data get persisted in a mongodb through an API and I also have full control over both if it's relevant.

The app will launch in 5 languages (it may grow later) so I can get 5 different 'versions' of the same string but I want the strings to be seen in the app in the language the app is in that moment (independently of the language it was stored in).

If possible, I would like to achieve this using native android translation capabilities, ie, shipping 5 XML files in the app, one for each language. I also want to have the server code as dumb as possible.

As of now, I can only think of storing an index in the db and then using a switch/case loop, presenting the data in the app view. I don't like this at all because the possible options will have to be hardcoded and any change would mean a new app version.

What's the best practice on this?

1

There are 1 answers

7
Julien Arzul On

From your comments, I understand that your actual problem is storing a spinner value in the database.

As you're saying in your question, you shouldn't store the string of the spinner but an integer representing that value. And then use your spinner with a List< Integer > instead of a List< String >.

An alternative to that int index with no meaning is an enumeration :

public enum SpinnerValues {
    EXAMPLE_1(R.string.example1_string),
    EXAMPLE_2(R.string.example2_string),
    EXAMPLE_3(R.string.example3_string);

    private int mStringResId;

    private SpinnerValues(int stringResourceId) {
        mStringResId = stringResourceId;
    }

    public int getStringResId() {
        return mStringResId;
    }
}

In that case, your spinner data would be List< SpinnerValue > and you would store your enum in database either with the ordinal or with the string representation of the enum (I would recommand the string value so that changing order of the enum values wouldn't break your database).