Problem ending programmatically an activity right after setting SharedPreferences - android

The problem I have now seems so basic that someone else must have faced it before me.
Here is the code, it just saves some preferences to be used later on:
val editor: SharedPreferences.Editor = sharedPreferences!!.edit()
editor.putString("activeFolder", "FavoriteFolder")
editor.commit()
//finish()
Before that sharedPreferences is declared at the class level like this:
private var sharedPreferences: SharedPreferences? = null
An it is initialized inside onCreate():
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
....
sharedPreferences = getSharedPreferences("MyNiceApp", MODE_PRIVATE)
....
}
After the code is executed I quit the activity by tapping the back button and all is good.
Finally here is the use case causing trouble. In the situation where there is nothing else to do after saving the preferences, instead of having the user manually tapping the back button I want the activity to automatically terninate and for that I call finish() (commented out in the code above). When doing that the activity closes as expected, but for some unknown reason the new preferences are not taken into account.
What do I need to do change to solve this issue?

call this
editor.apply()
you can remove
edit.commit()

I found the issue and learned something at the same time.
I was reading the new value of the sharedPreferences ("activeFolder") inside onCreate() but it appears that the onCreate() of the parent activity is not called after a finish().
Reading the new value of the sharedPreferences inside onStart() instead of inside onCreate() solves the problem.

I cant see any problem from your code, but I guess the code omitted may block your finish action? So you can print some log before and after your finish(), and see whether it has been executed.

Related

webview shows everytime the content of the last url when opening the app

I have been looking for a simple way to go to the prevues page when I start my webview activity instead of opening the main page every time I open the activity .
I tried to save the prevues page using SharedPreferences but it didn't work.
Do not call arbitrary methods on Activity until after super.onCreate() has completed. Move your getSharedPreferences() call inside of onCreate(), to be called after super.onCreate() has returned:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences("URL", MODE_PRIVATE);
settings.getString("url", "http://www.google.com");
// rest of your code goes here
}
When you initialize fields this way
SharedPreferences settings = getSharedPreferences("URL", MODE_PRIVATE);
the call to getSharedPreferences is made when the object (currently the Activity) is initialized. The problem is that this particular method has to be executed when the context is ready. Currently the context object is the Activity itself. So if you want to load shared preferences, you have to wait the activity to created and then you are able to load them. Here comes the onCreate method. You can safely load any context dependant information here after calling super.onCreate(...).

how to disable activities after first start

i an developping an app for android and i want to "disable" or "hide" some activitys after my start.
i tried it with the shared preferences... but it somehow didnt work...
// First Start
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if(mPrefs.getBoolean("firstLaunch", true)) {
mPrefs.edit().putBoolean("firstLaunch", false);
}
in my head my idea would look like that:
on first start:
enter the name (activity 1)
enter two friends (activity 2)
menu (activity 3)
when its not the first start is should start like that
menu
i hope you can help me
It works with SharedPreferences! But adding an entry is only half the way. You will also have to check this entry at the start of the application. Then it will work.
And you have to call mPrefs.commit() after adding the entry...
You're missing a commit() call in your preferences Editor.
This:
mPrefs.edit().putBoolean("firstLaunch", false);
should look more like this:
mPrefs.edit().putBoolean("firstLaunch", false);
mPrefs.commit();
try this to load a function or activity just one time
public void onResume()
{
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if(mPrefs.getBoolean("firstLaunch", true))
//here you add whatever you want to do one time
mPrefs.edit().putBoolean("firstrunas12", false).commit();
}

Android SavedPrefrerences loading?

I am trying to make an app(http://pastebin.com/uWkP6XNY) that when you press a button, creates a custom sms message. The user can go to a second activity (http://pastebin.com/MK2NPV5R) thats full of edit-texts that when saved, will bring back strings to be used to change the custom sms.
The issues I am facing is how I initalize my variables with whats in savedpreferences. I put this in my onCreate method.
smsintroduction = (sp.getString("intro", "")); //these are both strings initalized at the top
smsbody = (sp.getString("body", ""));
On start up, since it can't get "intro" from the dictionary, it goes to a null string. I want to be able to use my save() function in my second activity to save, which I Think I already do, but be able to change my two strings above.
I put the code above to set the strings in a method that completes the finalized textbody, but it keeps giving me emptystrings.
The only thing that gets created is "!", as shown in finishedtext().
It looks like in your MainActivity in onCreateOptionsMenu you are overriding the sp member previously set in onCreate with
sp = getSharedPreferences("prefs", 0);
Try removing that line or setting those shared prefs to a different instance member.

Android - Language change when clicking back

I have this settings section where I allow users to change the languages displayed within the app. When the user chooses a different language, the activity is reloaded so that the change of language can be applied. But the problem is, when the user clicks back right after changing the language, the language shown in the background activity is still the same.
So my question is, what should I do to apply the change of language when I get back to some activity on the background? I suppose I should do something to detect the change in onResume method, but I'm not sure what it is. If you have any suggestions, please let me know.
Thank you.
After several attempts, I have found the solution to my problem. On my onCreate method, I get the SharedPreferences that contains the value of current language, and get the current language:
SharedPrefrences languagepref = getSharedPreferences("language",MODE_PRIVATE);
String language = languagepref.getString("languageToLoad", Locale.getDefault().getDisplayLanguage());
Then, in my onResume method, I assign the value of the above mentioned variable language to a local variable, and update the value of language. Then I compare these two variables - if they are different, I will destroy the current activity and start another:
#Override
public void onResume(){
super.onResume();
String oldLanguage = language;
language = languagepref.getString("languageToLoad", Locale.getDefault().getDisplayLanguage());
if (!oldLanguage.equals(language)){
finish();
startActivity(getIntent());
}
}
And voila, that did the trick!
I would suggest using SharedPreferences. You can store a lang key with the associated value in there and update it when necessary. In your onResume() methods you can get the lang value and then populate views according the value stored.
SharedPreferences sharedPreferences;
sharedPreferences = this.getSharedPreferences("MyActivity", Activity.MODE_PRIVATE);
String lang = sharedPreferences.getString("lang", "en-GB");
SharedPreferences.Editor editor;
editor = sharedPreferences.edit();
editor.putString("lang", "en-US").commit();
That's the basics you need to get going.
Have you tried restarting the Activity after the change is done ?
You can Simply use
finish();
startActivity(getIntent());
to refresh an activity whenever it detects a preference change.
The built in back pressed function does not refresh the code,so do this after u you change the language.
#Override
public void onBackPressed()
{
//new MainActivity();
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
}
and in Main Activity class do this
public MainActivity() {
//1- This code is responsible for updating the change of all Strings from a language to another
//it will be called every time this activity is instantiated (da,since it is a constructor) , or when this activity gets
// called by an intent.
//2- Every String inside this Activity(ever fragment inside it ) will also be under the effect of change of language
LocalUtils.updateConfig(this);
}
Please review the following answer and add this to it. To get a full answer written by Roberto.B and LarsH:
Changing Locale within the app itself

Showing preference screen first time app is run and related questions

I have an app with 2 activities, the preference and the main activity, I need the preference screen to show first time the app is run so the user can do some configuration. I have checked through the answers on this topic and they don't seem very clear but I gather it has to do with checking that there are sharedpreference file is empty.
Can someone please give me a code to sort this out and on which activity would I put the code?
Also I am still in the developing stage so I already have my preferences setup how do I undo this?
Thanks in Advance
1) When your main activity starts check a boolean preference with the default set to false. If it is false, launch your preference activity, if it is true then you know you have saved it to be true!
SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
boolean haveWeShownPreferences = prefs.getBoolean("HaveShownPrefs", false);
if (!haveWeShownPreferences) {
// launch the preferences activity
} else {
// we have already shown the preferences activity before
}
2) In your preferences activity save the same boolean preference with a value of true in onCreate
SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("HaveShownPrefs", true);
ed.commit();
I assume that you're running an emulator, when you start the emulator you have the choice to "wipe saved data" when you start it so it will be like you started it as if you just started the application. Alternatively, you can go into settings -> Applications -> You app -> Wipe data.
In regards to your coding solution, I don't have anything handy at the moment, but what you should do is start your main activity, run a procedure/function to check if the sharedpreference file is empty, and if it is start the preference activity, otherwise run your main activity. Alternatively, instead of checking for the file to be empty, you could see if a value that you are looking for user input (for example UserID) is null or not. If that value isn't null that means that the application can continue.
I've sorted this out with this bit of code in my main activity
if (prefs.getString("edittextpref", null) == null)
{
startActivity(new Intent(this, Preferences.class));
return;
}
}
It just checks if one of your values is empty but you need to put this at the bottom of onCreate or else when you go back to the main page it will be blank.
I am doing something like this. And its works for me.
String path = "//data//data//"+this.getPackageName()+"//shared_prefs//feedbackpref.xml";
boolean exists = (new File(path)).exists();
if (exists) {
introWindowNavigate=false;
}

Categories

Resources