1

I wanted to add an option to change application language with Shared Preferences. I saved language like "en" or "fa" in Shared Preferences.

Now I need to set Shared Preferences data as language. I tried to use This code but I had some problems.

For using this code I should wrap my activities Context with:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(MyContextWrapper.wrap(newBase,languageFromPrefs));
}

I wrote an method for getting language from Shared Preferences called getString(Context context,String key,String defaultValue) and then edited that code to:

@Override
protected void attachBaseContext(Context newBase) {
    lang = App.Prefs.getString(newBase, App.Prefs.LANGUAGE_KEY,"fa");
    super.attachBaseContext(MyContextWrapper.wrap(newBase,lang));
}

It seems good but when I ran my app I saw a strange scene. At first run, app language was fa (Persian) and next time it automatically changed to en (English)!

[Note: Device language is currently English]


Here is my MainActivity:

(I commented codes that are not related to my problem)

public class MainActivity extends AppCompatActivity {

    EditText userText;
    Button embellishBtn;
    ImageView settings;
    String lang;

    @Override
    protected void attachBaseContext(Context newBase) {
        lang = App.Prefs.getString(newBase, App.Prefs.LANGUAGE_KEY,"fa");
        super.attachBaseContext(App.wrap(newBase,lang));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
/*
        userText = (EditText) findViewById(R.id.textBox);
        embellishBtn = (Button) findViewById(R.id.embellishButton);
        settings = (ImageView) findViewById(R.id.settings);

        App.SetFont.EditText(userText,this);
        App.SetFont.Button(embellishBtn,this);

        settings.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(getBaseContext(),getString(R.string.settings),Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        MarginActivity.isFirstRateMessage = true;



        Boolean isFirstOpen = App.Prefs.getBoolean(this, App.Prefs.FIRST_OPEN_KEY,true);

        if (isFirstOpen && TimeZone.getDefault().getDisplayName().toLowerCase().equals("iran standard time"))
        {
            App.Prefs.setString(this, App.Prefs.LANGUAGE_KEY,"fa");
            App.Prefs.setBoolean(this,App.Prefs.FIRST_OPEN_KEY,false);
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
        */
    }
/*
    public void onSettingsClick(View view)
    {
        startActivity(new Intent(this, SettingsActivity.class));
    }

    public void onEmbellishClick(View view)
    {
        if(userText.getText().toString().trim().length() > 0)
        {
            Intent intent = new Intent(this,EmbellishActivity.class);
            intent.putExtra("user_text",userText.getText().toString() + " ");

            startActivity(intent);
        }
        else
        {
            Animation shake = AnimationUtils.loadAnimation(this,R.anim.focus_zoom);
            userText.startAnimation(shake);
        }
        userText.setText(null);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("user_text",userText.getText().toString());
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        userText.setText(savedInstanceState.getString("user_text"));
    }
    */
}

And getString method ( App.Prefs.getString() ):

static String getString(Context context,String key,String defaultValue)
{
    SharedPreferences shared = context.getSharedPreferences("Prefs", MODE_PRIVATE);
    return shared.getString(key, defaultValue);
}


My application runs without any error. What I should do for solve this problem? What's wrong?

YektaDev
  • 438
  • 3
  • 11
  • 24
  • Please check below link: https://stackoverflow.com/questions/40221711/android-context-getresources-updateconfiguration-deprecated/40704077#40704077 – nomag Sep 16 '17 at 10:48
  • @nomag [LocaleHelper.java](https://gist.github.com/muhammad-naderi/0ff264e6cc07df904bc88a9f7efbe57d) is actually same with [This one](https://stackoverflow.com/questions/40221711/android-context-getresources-updateconfiguration-deprecated/40704077#40704077). – YektaDev Sep 16 '17 at 11:26

2 Answers2

1
@Override 
 protected void attachBaseContext(Context newBase) {
 super.attachBaseContext(MyContextWrapper.wrap
 (newBase,languageFromPrefs));
 }

This should be done in base activity which is extended by every activity in your project.

nomag
  • 300
  • 1
  • 7
  • I told with this code when I ran my app I saw a strange scene. At first run, app language was fa (Persian) and next time it automatically changed to en (English)! – YektaDev Sep 17 '17 at 07:47
0

You have to use this way for change language in run time

  SharedPreferences LanguagePreference = getSharedPreferences("SelectedLanguage", 0);
    String languageToLoad  = LanguagePreference.getString("Language", null);
    Locale locale =null;
    if(languageToLoad!=null && languageToLoad.equals("english"))
        locale =new Locale("en", "US");
    else if(languageToLoad!=null && languageToLoad.equals("tamil"))
        locale =new Locale("ta", "IN");
    else
        locale =new Locale("en", "US");
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.setLocale(locale);
    getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());
Raja
  • 2,775
  • 2
  • 19
  • 31