I am working with a service class that needs to know if the application is running in background or not. To do so, I created a boolean variable called activityVisible in my service. I need to update it constantly to know wether the app is in background or active.
I do this by sending true on the onResume() method in my activity like this:
intent.putExtra("Activity Visible", true)
and false on the onPause() method like this:
intent.putExtra("Activity Visible", false)
However, I print the extra in my service and it is always getting true. What I think it is happening is that once you put an extra, you cannot update its value, and that may be the reason it is not working.
Any way I can do the same in a different way? Or a solution to the way I am implementing this?
You can use SharedPreference to store the current state of the app.
to reference to the SharedPreference
SharedPreferences sp = getSharedPreferences("prefs", Context.MODE_PRIVATE);
to set a boolean in the shared preference, you need to use its editor, so apply this code in onPause, and onResume, while changing the "isVisible" value based on your need
boolean isVisible = true;
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("activity_visible", isVisible);
editor.apply(); // use apply to confirm the edit
and in order to get the value stored, you can simply refer to it using
boolean valueStored = sp.getBoolean("activity_visible", false /* Default value if not existed */);
Log.d("Activity State: ", "Boolean: " + valueStored);
and do whatever you want with that valueStored.
Related
I am working on android project built partially in kotlin and partially in java. I am trying to pass information from a kotlin fragment class to a java class. I have come to see that there is a problem with the passing of information as I do not receive the needed value. After some debugging I have seen that the information is successfully stored, however when the information from shared preferences is accessed, only the default value is returned.
This is the code in the kotlin class. When a button is clicked it changes the value of a boolean variable to the opposite one, sets the text of a button to true/false and saves the value of the variable in shared preferences.
btnStyle.setOnClickListener() {
styleHasChanged = !styleHasChanged;
if(styleHasChanged == true){
btnStyle.setText("true")
}else{
btnStyle.setText("false")
}
val sharedPref : SharedPreferences?= activity?.getPreferences(MODE_PRIVATE);
sharedPref?.edit()?.putBoolean("bla", styleHasChanged)?.apply()
}
This is the java class. Shared preferences is called inside a function which chooses a filepath based on the received value.
public static String getHtmlContent(Context context, String htmlContent, Config config) {
SharedPreferences sharedPreferences = context.getSharedPreferences("bla",MODE_PRIVATE);
boolean hasStyleChanged = sharedPreferences.getBoolean("bla", false);
//moj
String cssPath;
if (!hasStyleChanged) {
cssPath = String.format(context.getString(R.string.css_tag), "file:///android_asset/css/Style.css");
} else {
cssPath = String.format(context.getString(R.string.css_tag), "file:///android_asset/css/Style2.css");
}
This is where the problem arises. Shared preferences in the java class always fetches the default value, no matter if the button is clicked or not.
The getPreferences method implicitly uses the class name of the Activity as the preference file name. By passing "bla" as the file name to getSharedPreferences you're trying to fetch the saved value from a different file.
If you would like to access the same preferences accross your application, then either use getSharedPreferences (for both writing and reading the preference) with the same file name, or use the getDefaultSharedPreferences static method of PreferenceManager to obtain the default SharedPreferences instance.
You should change your code to something like this:
val sharedPref : SharedPreferences? = activity?
.getSharedPreferences("someFileName", MODE_PRIVATE)
sharedPref?.edit()?.putBoolean("bla", styleHasChanged)?.apply()
And the Java part:
SharedPreferences sharedPreferences = context
.getSharedPreferences("someFileName", MODE_PRIVATE);
boolean hasStyleChanged = sharedPreferences.getBoolean("bla", false);
Your context.getSharedPreferences("PreferencesFileName",MODE_PRIVATE) should be the same even when using the activity?.getPreferences("PreferencesFileName",MODE_PRIVATE). In you code it's not like that.
Plus a simple suggestion, because I'm not sure if you're clear on that. The bla is the key for your boolean value not your Preferences file name. I mean it could be, but it's better to separate.
I have a shared preference with no default value defined in the xml because I would like to set the default value programmatically when the main activity is created. The preference in question should either be the device language (if that language is available), otherwise the first available language, where the languages are defined in the appropriate xml as a string array.
I currently have, inside the main activity's onCreate method, the following
SharedPreferences preferences = getSharedPreferences(
getString(R.string.shared_prefs_key),
MODE_PRIVATE
);
String detailLanguage = preferences.getString(
getResources().getString(R.string.detail_display_language),
""
);
if (detailLanguage.isEmpty()) {
String deviceLanguage = Locale.getDefault().getLanguage();
String[] availableLanguages = getResources().getStringArray(R.array.pref_entry_values_detail_display_language);
boolean deviceLanguageSupported = false;
for (String availableLanguage : availableLanguages) {
if (deviceLanguage.equals(availableLanguage)) {
deviceLanguageSupported = true;
break;
}
}
preferences.edit()
.putString(
getResources()
.getString(R.string.detail_display_language),
deviceLanguageSupported ? deviceLanguage : availableLanguages[0]
).commit();
Debugging this code on the first run it enters the above if statement and sets the preference but the preference doesn't show as selected in the preference activity first time around (if I then select it myself, from then onward it appears selected as something).
Am I missing something? I am fairly new to Android. I tried the above based on some other similar SO questions.
PreferenceActivity and PreferenceFragment read preferences from a default preference file. To get access to those preferences you should use PreferenceManager.getDefaultSharedPreferences(context) method.
I am guessing that this is the reason you aren't seeing your changes: you write them to getString(R.string.shared_prefs_key) rather than to the default one.
Try changing your first line to this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
I know there must be douzens of answers to this question out there, but either i cant't find them or I don't understand them.
The Question:
How do I get my app to exactly start as it was left?
F.e. dynamicly added checkBoxes shouldn't dissapear!
There is no "out of the box" way of doing it. You could save the current state of your Activity in some way (More on persistence)
Then you need to be able to rebuild the desired state of the persisted state in your Activity lifecycle
You could save and load with the shared preferences for example:
public void saveState(YourState state) {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
sharedPreferences.edit()
.putString("CustomAtt", state.getCustomAtt())
}
public YourState loadState() {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
String customAtt = sharedPreferences.getString("CustomAtt", "DefaultValue")
return new YoutState(customAtt)
}
And use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
YourState state = loadState();
// Rebuild your activity based on state
someView.setText(state.getCustomAtt())
}
You can store such values in SharedPreferences.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
It is using key-value approach for saving. So you can save some values and read it from SharedPreferences whenever you want to.
This is the best approach for small data, that can be used on the app launch. So you can quit your app and the data is still present - so can be read on the next app launch.
Or save the condition of your program to a text file, so that the program can "translate" it back into conditions before it stops, or what I do not recommend, it saves every object created with ObjectOutputStream.
I need to start an activity(tutorial) on my first app launch. I figured i could write this in my main but then i realized once the app is closed and start again it would just start the tutorial again.
Boolean first = true;
if(first){
Intent i ......
first = false;
}
so i thought about creating a database or writing a value in a file and saving the Boolean value in that. Is there a easier way for this? thanks in advance
You can use preference for this. You can implement following codes on your onCreate method
SharedPreferences prefs = PreferenceManager.getDefaultPreferences(getApplicationContext());
boolean first = prefs.getBoolean("key_first_launch", true);
if (first)
// show your tutorial
else
// dont show your tutorial
When first tutorial complete, change preference value
SharedPreferences prefs = PreferenceManager.getDefaultPreferences(getApplicationContext());
prefs.edit().putBoolean("key_first_launch", false).commit();
You need to save that information, for instance with SharedPreferences, so that it is persistent and read its value when the application is started.
See:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html#preferences
I have a blank-ish Android Project and what I want to do is take the user to a different "page/screen" if it is their first time only.
I know the logic for this but since I'm new to Android, I'm unsure of how to code this.
Below are the steps I believe I need to take in order to accomplish this:
App loads. If Local storage contains setting "FirstTimeUser", then it is not their first time using the app. Show the MainActivity page. If FirstTimeUser setting does not exist, it is their first time using the app (or they have uninstalled and reinstalled it), so instead, show WelcomeActivity page.
After viewing Welcome activity page, create FirstTimeUser setting and set to False.
But how do I code this for an Android app?
Use shared preferences as shown:
//declare as global
SharedPreferences prefs = null;
//and in your onCreate method:
prefs = getSharedPreferences("packageNameHere", MODE_PRIVATE);
if (prefs.getBoolean("firstrun", true)) {
//do stuff here if first run
//make sure to flag the boolean as false
prefs.edit().putBoolean("firstrun", false).commit();
}
else{
//if not first run, do something else
}
There is something called "SharedPreferences" that i believe your looking for.
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html