I am adding multiple language facility in my android app.
Whenever I change the language it changes fine. But after reopening the app its again showing the choose language screen.
I want to save the last selected language, so next time when user reopen the app it should not show the choose language screen it should directly go to the next page and should display the items in the language which was last selected.
What to do? Any solutions?
Please check the below code.
In this code
where i have to store in SharedPreferences and where i have to get the sharedpreference
@Override public void onItemSelected(SelectableItem selectableItem) {
List<Item> selectedItems = adapter.getSelectedItems();
if(selectableItem.getName().equals("English")){
if (userSessionManager.isLoggedIn()) {
Intent intent = new Intent(LanguageListActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
setLanguage("en");
} else {
Intent intent = new Intent(LanguageListActivity.this, LoginActivity.class);
Log.d("Login", "firgage");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
setLanguage("en");
}
}else if(selectableItem.getName().equals("Hindi(हिंदी)")){
if (userSessionManager.isLoggedIn()) {
Intent intent = new Intent(LanguageListActivity.this, MainHindiActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
setLanguage("hi");
} else {
Intent intent = new Intent(LanguageListActivity.this, LoginhindiActivity .class);
Log.d("hLogin", "firhin");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
setLanguage("hi");
String lang = "hi";
}
}
}
protected void setLanguage(String language){
mylocale=new Locale(language);
Resources resources=getResources();
DisplayMetrics dm=resources.getDisplayMetrics();
Configuration conf= resources.getConfiguration();
conf.locale=mylocale;
resources.updateConfiguration(conf,dm);
//Intent refreshIntent=new Intent(LanguageListActivity.this,MainActivity.class);
finish();
//startActivity(refreshIntent);
}
I want to save the last selected language - For this you need to use SharedPreferences
For SharedPreferences reference : shared preferences
To store in SharedPreferences :
SharedPreferences sharedPref = getActivity().getPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("lang", language);
editor.commit();
To get the SharedPreferences :
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
MY_PREFS_NAME, Context.MODE_PRIVATE);
String language = sharedPref.getString("lang", null);
Check in activity onCreate that if this shared preference is null or not. if null then language screen and if not null then home screen.
Tutorial : SharedPreferences