How to set app background via the SharedPreferences? - java

I want to allow users to change my app's background from the settings (for the Main_UI activity class). I am not able to store the uri in a string since there is no startActivityForResult() method that could extract the intent's uri (The Preferences only allow starting an intent, preferably to other settings)(I tried creating custom Preference Class but again, not startActivityForResult). I tried doing it via the menu options, taking the uri and creating a drawable from it. But when I apply that drawable to my RelativeLayout instance, it says its supported only beyond API 16. Mine is 15.
Any help would be really appreciated, since this android is getting on my nerves.

Use this approach to support lower version API(s):
if (Build.VERSION.SDK_INT > 15)
yourLayout.setBackground(yourDrawable);
else
yourLayout.setBackgroundDrawable(yourDrawable);
Using SharedPreferences
In the settings activity:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = settings.edit();
edit.putString("bg_drawable_uri", bgDrawableUri);
edit.commit();
And in main activity:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.getString("bg_drawable_uri", "default_uri");

I know this is very old and probably there might be better ways today, but what worked for me was to just create an ImageView, set the uri and then retrieve the drawable from the ImageView, like so:
ImageView imageView = new ImageView(context);
imageView.setImageURI(someUri);
getWindow().setBackgroundDrawable(imageView.getDrawable());

Related

Writing tests for preferences, keep getting `android.content.res.Resources$NotFoundException` when accessing preferences

I am just starting to learn testing on Android and this is driving me crazy. The feature works fine but I cannot get my tests to run. I am trying to read a value from SharedPreferences and compare it to the content of a TextView. I am using Espresso on Android Studio 2.3.3.
This line String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne)); causes this android.content.res.Resources$NotFoundException: String resource ID #0x7f09004d exception. This is essentially the same code that I use in my Fragments to access shared preferences.
I could not find anything referencing this same problem. I feel like I just have a simple configuration error but I can't figure it out. Thanks in advance.
Here is my entire test:
#Test
public void setsPlayerNamesFromSettings(){
Context context = getInstrumentation().getContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne));
onView(withId(R.id.LpCalculatorTextPlayer1Name)).check(matches(withText(player1Name)));
String player2Name = sharedPreferences.getString(context.getString(R.string.KEYplayerTwoDefaultNameSetting), context.getString(R.string.playerTwo));
onView(withId(R.id.LpCalculatorTextPlayer2Name)).check(matches(withText(player2Name)));
}
If it's any assistance, here's code from my Fragment that access SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
mLpCalculatorModel.setLpDefault(Integer.parseInt(preferences.getString(getString(R.string.KEYdefaultLpSetting), "8000")));
mLpCalculatorModel.setPlayer1Name(preferences.getString(getString(R.string.KEYplayerOneDefaultNameSetting), getString(R.string.playerOne)));
mLpCalculatorModel.setPlayer2Name(preferences.getString(getString(R.string.KEYplayerTwoDefaultNameSetting), getString(R.string.playerTwo)));
mLpCalculatorModel.setAllowsNegativeLp(preferences.getBoolean(getString(R.string.KEYallowNegativeLp), false));
tvPlayer1Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
tvPlayer2Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
getInstrumentation().getContext()
This returns a Context representing your androidTest source set. If your resources are elsewhere (e.g., main), use:
getInstrumentation().getTargetContext()

Shared Preferences getint not returning default value

I am using shared preferences and would like the default value to be 1 when there are no preferences found.
My code
int currentRadio;
...
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
currentRadio = prefs.getInt("radioSelected", 1);
I am unsure why I am not getting 1 for the default value.
To test I would uninstall the app from my phone then launch the app to my phone from android studio. Every time I get 2 as the default value. However, if I just clear the data from the app, I get 1 as the default value.
Any help is appreciated, thank you.
Just Go through this:
SharedPreferences sp = getSharedPreferences("your_prefs",Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
Then you can get it as:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);
The SharedPreference interface gives you access to the an xml file, and a easy way to modify it through its editor. The file is stored in /data/data/com.your.package/shared_prefs/ and you can access it onlu through this SharedPreference API
Actually, you also need to provide a default value to getInt which is returned when an int with the key your_int_key could not be found. Something like this:
int myIntValue = sp.getInt("your_int_key", -1);
where -1 is the default value
Also, If you use API 9 or above you should use apply() instead of commit()
declare prefs like:
prefs = PreferenceManager.getDefaultSharedPreferences(context);
It would be happening due to you wrong implementation of shared preference.
Do one thing search for the key "radioSelected" in you app. if it found at any other place to save the value in shared preference, then make it comment.
Or just share your complete shared preference file.
If using android-21 the problem is not with preferences. Its with backup manager
Add in manifest file
android:allowBackup="false"

initaialize variable once in android app then use and save that for futher reuse

My question is this--
I have an app that should limit a button click ,say upto 5 clicks ,in whole lifetime of the app.
Preciously at 6th click of a certain button it should not read that OnClick event ,no matter how many times the app is opened or closed.
Guys im an average programmer and im enough aware of both android and java.Any help is appreciated. :)
You can use Shared Preferences to store the value and retrieve it.
// Write Shared Preferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putInt("ClickCounter", counter);
sharedPreferencesEditor.apply();
// Read Shared Preferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
int clickCounter = sharedPreferences.getInt("ClickCounter", 0);

Resetting preferences when using PreferenceScreen

I am loading a PreferenceScreen from an xml file to use as the screen to configure a new event so I'm attempting to clear and reset the values of the SharedPreference this activity is using. The problem I'm encountering is that when attempting to move to using a named preference manager, it seems the preference gets cleared but when I select an EditTextPreference element, the old data is still the default entered text on the popup.
In my onCreate method I'm attempting to initialize the preferences, clear them, then set to default values. My understanding from the dev resources were that there's no way to clear/reset in one step..
private static final String PREFNAME = "newmeetingactivity.preferences";
//load preferences and set name
addPreferencesFromResource(R.layout.newmeeting_preferences);
getPreferenceManager().setSharedPreferencesName(PREFNAME);
getPreferenceManager().setSharedPreferencesMode(MODE_PRIVATE);
//Clear the preferences
_sharedPreferences = getPreferenceManager().getSharedPreferences();
SharedPreferences.Editor ed = _sharedPreferences.edit();
ed.clear();
ed.commit();
//Load default preferences from file again
PreferenceManager.setDefaultValues(this, _sharedPreferences.toString() , MODE_PRIVATE, R.layout.newmeeting_preferences, true);
Edit: To try to better explain what I'm attempting to do (in case my approach is way off): I need to clear shared preferences used on a given activity while not interfering with the settings from other activities (as they should persist indefinitely).
Could you instead try using the PreferenceManager.getDefaultSharedPreferences(context) to get your prefs.
Edit:
adb shell into your application after you choose to reset the values. If you look at the preference file you will see that it's default value has been set. Try refreshing your activity. One way I did this was by simply killing it from the Applications menu. When the activity restarts it will have the expected default value.

How do I get the SharedPreferences from a PreferenceActivity in Android?

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this:
public class FooActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.preference);
}
}
The javadoc of PreferenceActivity PreferenceFragment states that
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.
But how I get the name of the SharedPreference in another Activity? I can only call
getSharedPreferences(name, mode)
in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the
settings of a specific application or an activity. For supporting
this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as
“Shared Preferences” across various activities in an application (note
currently it cannot be shared across processes). Or it can be
something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove() and clear() to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.
Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.
String preferencesName = this.getPreferenceManager().getSharedPreferencesName();
The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.
Declare these methods first..
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Then call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
call this when you want to get a pref:
getPref("myKey", getApplicationContext());
Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
which simplifies everything even further
Example:
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...
public class global {
public static Activity globalContext = null;
and set it in the main activity create
#Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
global.sdcardPath,
""));
super.onCreate(savedInstanceState);
//Start
//Debug.startMethodTracing("appname.Trace1");
global.globalContext = this;
also all preference keys should be language independent, I'm shocked nobody has mentioned that.
getText(R.string.yourPrefKeyName).toString()
now call it very simply like this in one line of code
global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
if you have a checkbox and you would like to fetch it's value ie true / false in any java file--
Use--
Context mContext;
boolean checkFlag;
checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
Try following source code it worked for me
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");

Categories

Resources