Reputation: 31
I now have a spinner in the first activity in the app containing a list of languages available and I need to restart the activity to change the language of the app (I am using context wrappers). But my code keeps "recreating" the activity and it never stops:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
Session.setLang(position);
String name = lang_name[position];
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
editor.putString("locale", name);
editor.commit();
recreate();
}
Is there anyway I can restart an activity from a spinner item selection?
Upvotes: 1
Views: 669
Reputation: 31
Guys if you are interested, at last I worked around the first trigger of the onItemSelected() call by adding a first_trigger flag to the event listener and replaced recreate() as follows, everything works fine now:
lang_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
boolean first_trigger = true;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
LoginSession.setLang(position);
if(first_trigger){
first_trigger = false;
}else{
String name = lang_name[position];
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
editor.putString("locale", lang_name);
editor.commit();
Intent intent = new Intent(getBaseContext(), Login.class);
startActivity(intent);
overridePendingTransition(0,0);
finish();
overridePendingTransition(0,0);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent){
LoginSession.setLang(0);
}
});
Upvotes: 2
Reputation: 11481
my code keeps "recreating" the activity and it never stops:
Be carefull while setting onItemSelection listener. Set your listener only after initializing the spinner, otherwise when you set the default item , it will execute the onItemSelected
and will keep recreating the activity as per your code.
Upvotes: 1