How to recall onCreate( ) when onBackPressed( ) and go to previous activity? - android

MyApp testing is multi language change. http://www.androhub.com/android-building-multi-language-supported-app/ After I choose radio button, it changes language in current activity. But when I go back previous activity, it doesn't change language. So, I want to recall onCreate when I click back button. Or How to refresh current activity?
onCreate ()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
txt = (TextView) findViewById(R.id.txt);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioEng = (RadioButton) findViewById(R.id.eng);
radiohi = (RadioButton) findViewById(R.id.hi);
// Initialization
pref = getSharedPreferences("MyPref", Activity.MODE_PRIVATE);
editor = pref.edit();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
String lang = "en"; // Default Language
switch (i) {
case R.id.eng:
lang = "en";
break;
case R.id.hi:
lang = "hi";
break;
default:
break;
}
changeLocale(lang); // Change Locale on selection basis
}
});
loadLocale();
}
changeLocale
private void changeLocale(String lang) {
if (lang.equalsIgnoreCase(""))
return;
Locale myLocale = new Locale(lang); // Set Selected Locale
saveLocale(lang); // Save the selected locale
Locale.setDefault(myLocale); // set new locale as default
Configuration config = new Configuration(); // get Configuration
config.locale = myLocale; // set config locale as selected locale
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); // Update the config
}
saveLocale & loadLocale
private void saveLocale(String lang) {
editor.putString("save", lang);
editor.commit();
if (lang.equals("en")) {
radioEng.setChecked(true);
} else {
radiohi.setChecked(true);
}
}
private void loadLocale() {
String lang = pref.getString("save", "");
if (lang.equals("")) {
radioEng.setChecked(true);
} else {
changeLocale(lang);
}
}

give resultCode when back from current activity, or save configuration, then check configuration on activity resume for language change

I think you should finish the previous activity and recreate it, you can use LocalBroadcast.

You can call onCreate method on back press by handling back press event.
#Override
public void onBackPressed() {
onCreate(new Bundle());
}
If you are using API 11 then use below code and also if above code doesn't work.
Intent intent = getIntent();
finish();
startActivity(intent);

While using the recreate method works by doing
this.recreate()
It was only added in API level 11. If you want to include more devices you can check the API level and implement both the recreate method as well as
Intent intent = getIntent();
finish();
startActivity(intent);
You can use both by making an if statement like...
if (android.os.Build.VERSION.SDK_INT >= 11){
//Code for recreate
recreate();
}else{
//Code for Intent
Intent intent = getIntent();
finish();
startActivity(intent);
}

Intent intent=new Intent(Current_Activity.this,Current_Activity.class);
startActivity(intent);
finish();
instantiate a new intent in your onBackPressed()

Since you are using two activities when you create intent from first activity to second activity the first activity onStop() is called and activity is put to back stack.When you press back button the first activity onCreate() is not called again but onResume() is called and activity is resumed.
So the logic that your are trying to should be done in onResume() such that it will be called every time when you press back button.For more reference check this.
https://developer.android.com/guide/components/activities/activity-lifecycle.html

Related

Changes are not applied to all the activities

I implemented night mode in my app.User can change the night mode settings in profile activity.The order of activities are as follows.
TabbedActivity>>DisplayActivity,ProfileActivity
The changed settings are applied only in current activity.(i.e profile activity).If the user presses back button,changes are not applied to that activities.Anyone help me to apply changes to all the activites.When we close the app and open again.changes are applied.But back press doesn't work.
This is the code I am using.
#Override
protected void onCreate(Bundle savedInstanceState) {
final SharedPreferences sharedPreferences =
getSharedPreferences("NIGHT_MODE", MODE_PRIVATE);
int result=sharedPreferences.getInt("NIGHT_MODE_OPTION",0);
if (result==2){
setTheme(R.style.darkTheme);
}else setTheme(R.style.AppTheme);
loadLocale();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final SharedPreferences.Editor editor = getSharedPreferences("NIGHT_MODE", MODE_PRIVATE).edit();
if (result==2){
night.setChecked(true);
}
night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
editor.putInt("NIGHT_MODE_OPTION",AppCompatDelegate.MODE_NIGHT_YES);
editor.apply();
startActivity(getIntent());
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
editor.putInt("NIGHT_MODE_OPTION",AppCompatDelegate.MODE_NIGHT_NO);
editor.apply();
startActivity(getIntent());
}
}
});
}
Since you are not considering Android lifecycle. You configure everything inside onCreate. However, while switching between activities current activity's lifecycle change accordingly. Here is lifecycle is explained very well
Solution:
When you come back to the previous activity, onResume is called. You should apply all changes inside this method
override fun onResume() {
super.onResume()
//Read your settings from SharedPrefs then apply, here
}
'i think the better practice would to restart/reset app everytime the theme is changed'
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();

Change language without restarting activity

I have a method that translates my application from English to Swedish and back again if the user so wishes. However, I don't really like the fact that the activity restarts every time because it's giving me a hard time with the savedInstaceState and I've had several crashes because of this.
Here's how my method that changes language looks:
public void setApplicationLanguage(String language) {
myLocale = new Locale(language);
Resources res = activity.getResources();
DisplayMetrics display = res.getDisplayMetrics();
Configuration configuration = res.getConfiguration();
configuration.locale = myLocale;
res.updateConfiguration(configuration, display);
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
}
Is there any chance that the same function can be applied without the:
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
?
Try this
I also had this issue.I used the code below and then it changed the language without refreshing the activity
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);
/*Intent refresh = new Intent(this, AndroidLocalize.class);
startActivity(refresh);*/
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
lblLang.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
// Checks the active language
if (newConfig.locale == Locale.ENGLISH) {
Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
} else if (newConfig.locale == Locale.FRENCH){
Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
}
}
declare in Manifest android:configChanges="locale"
You can replace the code:
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
With the method from Activity class:
recreate();
I hope your minimum SDK version will support because it was introduce in SDK 11. Your activity will be recreate as a new instance remember! Everything will be started afresh. From my experience it is fast compared to making a new Intent. But if you want to pass some data the method of using Intent is better than that! You can add extras to the Intent.
Create a singleton class:
public class Singleton {
private static Singleton mInstance = null;
private int repeat = 0;
public int getRepeat() {
return repeat;
}
public void setRepeat(int repeat) {
this.repeat = repeat;
}
}
Now you have a method that you can set and get the data, so make a method and put it under onResume() method, call your method and you can get and set the data like this:
Singleton.getInstance().setRepeat(1);
Singleton.getInstance().getRepeat();

How to change the language of the app when THE USER selects the language?

How to change the language of the app when THE USER selects the language?
I want to do almost this: http://snowpard-android.blogspot.com.br/2013/03/programmatically-change-language-in.html?google_comment_id=z13isbsazkf3hzea504celo5oy3rjzbyevo0k
but instead of changing the language of a textView, I want to create a button with the name of the language, and when the user clicks on it, it goes to a second page already translated. I already created new values with the languages, but can't think about a code that could open another page with those strings. Could anyone help me, plssss?
I would suggest to pass the language name as an intent extra in the first activity and get it in the second activity and update the language accordingly. Consider the following
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// findViewbyId here for button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
intent.putExtra("lang", "fr");
startActivity(intent);
}
});
}
}
and in the other activity
public class OtherActivity extends AppCompatActivity {
#Override
private void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String lang = getIntent().getStringExtra("lang") == null ? getIntent().getStringExtra("lang") : "en";
// assuming this is the method you have to call to change the language
changeLang(en);
}
}
Hope this helps.
use localization for achieving this on on click .
String languageToLoad = "hi"; // change your language her this is for hindi
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.main);

SharedPrefs is resetting after Setting Locale of the Android Application

I've create an activity to change the locale of the application to load resources of the selected language and I restart the application,moreover I'm keeping an integer value as the app state using sharedpreferences,after setting the locale via the following code,the next time that I open the application the mentioned state does not have the correct value!!!!But,when I remove the language setting there isn't any problem with the state of the application!
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
/*
* Intent refresh = new Intent(this, AndroidLocalizeActivity.class);
* startActivity(refresh); finish();
*/
PrefManager _p = new PrefManager(getApplicationContext(), PrefConfigNames.LANGUAGE_APP_CONFIG);
_p.setStringValue(GeneralPrefKeyNames.LANGUAGE, lang);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
setResult(RESULT_OK, null);
finish();
I cannot get what happens to sharedpreferences(I've used open source securepreferences (CodeProject article)in this app)
here!!!
Thanks in advance
Edit#1
PrefManager.java
public class PrefManager {
private SecurePreferences _securePreferences = null;
public PrefManager(Context context, String PrefName)
{
_securePreferences = new SecurePreferences(context, PrefName);
}
public void setStringValue(String key, String value)
{
_securePreferences.edit().putString(key, value).commit();
}
}
Edit#2
Something which is so weird is that the state of the application stored in the sharedprefs has the correct value when I debug or run the application from eclipse (debug or run as an android application)!!!but when I rerun it on the phone it has the default value!!!Please help me solve this issue!
Edit#3
I found out that there was a problem with relaunching the application using the following lines,is there another way to relaunch the app without any problem???Or even a better way (to update the language without relaunching the app)?
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
I've tried the following link to achieve the second mentioned approach
Changing locale: Force activity to reload resources?
,but it is not being raised after the following line
res.updateConfiguration(conf, dm);
Thanks in advance
I finally got the solution,in the onPause method I save the currently saved language in the sharedprefs and after changing the locale in the setting activity and returning to the previous activity in the onResume method I compare the newly saved lang with the value kept in the onPause,and if these two are not equal I call recreate method.
#Override
protected void onResume()
{
super.onResume();
SharedPreferences _sPreferences = getSharedPreferences(PrefConfigNames.LANGUAGE_APP_CONFIG,
Context.MODE_PRIVATE);
String resumeLang = _sPreferences.getString(GeneralPrefKeyNames.LANGUAGE, "En");
if (!currentLang.equals(resumeLang))
recreate();
};
#Override
protected void onPause()
{
SharedPreferences _sPreferences = getSharedPreferences(PrefConfigNames.LANGUAGE_APP_CONFIG,
Context.MODE_PRIVATE);
currentLang = _sPreferences.getString(GeneralPrefKeyNames.LANGUAGE, "En");
super.onPause();
};
You should commit() the values

How to change language locally in portrait AND landscape mode

i have to implement an app prototype that should have the possibility to change the language inside the app.
My code:
...builder.setItems(langList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedLanguage = which;
if (selectedLanguage != -1) {
Configuration configuration = new Configuration(getResources().getConfiguration());
String currentLanguage = configuration.locale.getLanguage();
switch (selectedLanguage) {
case 0:
if (currentLanguage.equalsIgnoreCase("de")) {
configuration.locale = Locale.ENGLISH;
} else {
return;
}
break;
case 1:
if (currentLanguage.equalsIgnoreCase("en")) {
configuration.locale = Locale.GERMAN;
} else {
return;
}
break;
default:
break;
}
getResources().updateConfiguration(configuration, null);
Intent intent = new Intent(getActivity(), DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
dialog.dismiss();
}...
and it works nice. But the problem is - as you change the display mode (portrait <=> landscape) loads the current system language (respectively strings.xml in values folder) again.
has anyone already experience with it, or maybe a suggestion how could I solve this problem?
thanks in advance..
you can when the user select its language save it in preferences and in oncreate method check if preferences have value for language or not if not load the default language
by default the change orientation will call the oncreate method so fell free to add checking code in it
You can know problematically when the orientation change happens because the onConfigurationChanged() lifecycle event happens.
See the following example for how you can detect the orientation change. http://techblogon.com/android-screen-orientation-change-rotation-example/
When the configuration changes you can store any values you need. Please note that you can also store the values in a setting when they are first set.
When creating the activity (onCreate()) you can read the orientation and set any appropriate values.
In summary, review the Activity lifecycle, there are relevant events there you can trigger on.
so, I solved the problem using SharedPreferences:
... default:
break;
}
SharedPreferences preferences = getActivity().getSharedPreferences("SETTINGS_FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("currentLanguage", configuration.locale.getLanguage());
editor.commit();
getResources().updateConfiguration(configuration, null); ...
then I implemented method setCurrentLanguage() in my MainActivity/MainFragment:
... protected void setCurrentLanguage() {
Configuration configuration = new Configuration(getResources().getConfiguration());
SharedPreferences preferences = getSharedPreferences("SETTINGS_FILE", Context.MODE_PRIVATE);
String restoredLanguage = preferences.getString("currentLanguage", null);
if (restoredLanguage.equalsIgnoreCase("en")) {
configuration.locale = Locale.ENGLISH;
getResources().updateConfiguration(configuration, null);
}
} ...
and finnaly i call this method in every activity/fragment before setContentView(...):
// in an activity
... protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCurrentLanguage();
setContentView(R.layout.activity_dashboard); ...
// or in a fragment
... public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setCurrentLanguage();
View rootView = inflater.inflate(R.layout.fragment_preferences,
container, false); ...
Thanks again for your help ;)

Categories

Resources