I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other. My simple code like this:
private SharedPreferences prefs;
private static final String SELECTED_ITEM = "SelectedItem";
private SharedPreferences.Editor sharedPrefEditor;
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
else if (id == R.id.web)
final CharSequence[] items={"English","Arabic","Russian"};
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("Choose Website");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
webView = (WebView) findViewById(R.id.webView);
int website=current_page;
if("English".equals(items[which]))
{
webView.loadUrl("https://english.com");
website=("https://english.com");
}
else if("Arabic".equals(items[which]))
{
webView.loadUrl("https://arabic.com");
website=("https://arabic.com");
}
else if("Russian".equals(items[which]))
{
webView.loadUrl("https://russian.com");
website=("https://russian.com");
}
saveSelectedItem(website);
}
});
builder.show();
}
private int getSelectedItem() {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
return prefs.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
}
Why are you setting a String to an int variable (website)
You should probably save the language as a preference (String). and then when you load up the app, read the language preference and determine the website from there.
something like below.
public String getWebsite(){
SharedPreferences prefs;
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
String language = prefs.getString("Language", "English");
String website = "";
switch(language){
case "Russian":
website = "russian.com";
break;
default:
website = "english.com";
}
return website;
}
private void saveSelectedItem(String language) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt("language", language);
sharedPrefEditor.commit();
}
when you call save selected item, just pass in items[which] instead of which
in saveSelectedItem(website);
You are passing a string and the method requires int
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
For saving your data in shared preferences
i recommend to use GSON
i recommend to make a class for example
public class WebsiteData
{
#SerializedName("lang")
#Expose
private String lang ;
#SerializedName("website")
#Expose
private String website;
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang= lang;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website= website;
}
}
When user select language create new object and set the language with the chosen language and the set the website with its corresponding value
Then Turn object into String by Gson Like following :
Gson gson = new Gson();
String dataToSave = gson.toJson(WebsiteData);
String loadedString = getUserData(context);
WebsiteData loadedData = gson.fromJson(loadedString, WebsiteData.class);
to save and load data use the following methods :
public void saveUserData(Context context, String data) {
SharedPreferences sharedpreferences;
sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(DATA_KEY, data);
editor.apply();
}
public String getUserData(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
return sharedpreferences.getString(DATA_KEY, null);
}
Related
I want to use sharedprefrence string form another activity but the value is not being passed it always passes the default value?
Creation of variable toast Shows inp value but value is not being passed
name_next = (Button) findViewById(R.id.name_next);
sp= getSharedPreferences("name_pref",Context.MODE_PRIVATE);
name_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inp = nameInput.getText().toString();
SharedPreferences.Editor editor= sp.edit();
editor.putString(inp,nameInput);
editor.commit();
Toast.makeText(com.calmo.name.this,"welcome "+inp,Toast.LENGTH_LONG).show();
Intent intent = new Intent(name.this,MainActivity.class);
startActivity(intent);
}
});```
**Calling **
**The Value is always returned as error that is default**
``` SharedPreferences sp=getApplicationContext().getSharedPreferences("name_pref",Context.MODE_PRIVATE);
String name_in =sp.getString("inp","Error");
name.setText(name_in);
public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;
private String demo_string = "demo string's key"
public AppSharedPreferences() {
}
public static void init(Context context)
{
if(sharedPref == null)
sharedPref = context.getSharedPreferences(
context.getPackageName(), Activity.MODE_PRIVATE);
}
public static void setDemoString(String demoString) {
Editor prefs = sharedPref.edit();
prefs.putString(demo_string, demoString);
prefs.apply();
}
public static String getDemoString() {
return sharedPref.getString(demo_string, "");
}}
Put this wherever u want to use shared prefs:
AppSharedPreferences.init(this);
You can exchange this for activity or context, depending on where you use the code.
To set value in preference, use this code:
AppSharedPreferences.setDemoString("Some Text");
To get the value from preference:
String text = AppSharedPreferences.getDemoString();
Remove
inp = nameInput.getText().toString();
under onclick
and change
editor.putString(inp,nameInput);
to
editor.putString("inp",nameInput.getText().toString());
I'm working on an application and I have to save changes made by the user ... the user going to click on an image, it's going to change the color. And I want to save that change.
I'm not sure how to do that actually. Here is where I want to make the change.
All I know is I need to use SharedPreferences .
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
bookmark.setOnClickListener(new View.OnClickListener(){
private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
});
So does anybody have an idea of how to save changes made to the above code?
Note : I'm not using database
In shared preferences data is stored in the “key-value” format. As far as I understand, you need to save two fields and it will be something like this:
“booking: true”
“bookmarkImageResource: 15670341274”
Here is a convenient way to do it:
Step one – create a new class SharedPrefs:
public class SharedPrefs {
private static final String SHARED_PREFERENCES_NAME = "user_prefs";
private static final String BOOKING_INFO = "booking";
private static final String BOOKMARK_IMAGE_RESOURCE_INFO = "bookmarkImageResource";
private final SharedPreferences prefs;
public SharedPrefs(Context context) {
prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public boolean saveBookingInfo(String bookingInfo, String bookmarkImageResource) {
return prefs.edit()
.putString(BOOKING_INFO, bookingInfo)
.putString(BOOKMARK_IMAGE_RESOURCE_INFO, bookmarkImageResource)
.commit();
}
public Pair<String, String> getBookingInfo() {
return new Pair<String, String>(
prefs.getString(BOOKING_INFO, ""),
prefs.getString(BOOKMARK_IMAGE_RESOURCE_INFO, ""));
}
public void clearAll() {
prefs.edit().clear().apply();
}
}
Step two - use your class wherever you need to save, get or clear data!
In you case:
SharedPrefs prefs = new SharedPrefs(this); // or getActivity() instead of this if we are in a fragment
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
}
prefs.saveBookingInfo(String.valueOf(bookmarking), String.valueOf(bookmark));
Hope this will help you =)
Have a good day & happy coding!
/**
* Get a shared preferences file named Const.SHARED_PREFERENCES_FILE_NAME, keys added to it must be unique
*
* #param ctx
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences(Context ctx) {
return ctx.getSharedPreferences(Const.SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
}
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
Using SharedPreferences is very easy. You need to define a key which you will use to retrieve the data later. You can store Strings, ints, floats, booleans... You need to provide the context.
Context context = getApplicationContext();
To write data, use this code.
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("color", "blue");
editor.apply();
To retrieve data, use this
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
String color = mPrefs.getString("color", "defaultValue");
You can easily change the type from String to other types that might best suit your needs.
Hope it helps.
Hope its help you
SharedPreferences sharedPrefs = getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
private boolean bookmarking = sharedPrefs.getBoolean("bookmarking",true);//To get value that saved in SharedPreferences
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
}
else{
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
bookmark.setOnClickListener(new View.OnClickListener(){
// private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
});
I have created some editText box in my activity it's like an Update form and all I am trying to do now is to set random value to all the check box whichever is left blank while hitting the submit button. what I am getting is... getting value in only ETname edittext box and if I am clicking on submit button again my app is crashing and even if I am giving any value by myself to ETname and submitting it my app is crashing. please help.
public class User_Profile extends AppCompatActivity implements View.OnClickListener {
private Button Update;
private Context aContext;
private EditText ETname, ETsurname, ETadd, ETpin, ETmail, ETph;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userprofile);
ETname = (EditText)findViewById(R.id.edit_name);
ETsurname = (EditText)findViewById(R.id.edit_sur);
ETadd = (EditText)findViewById(R.id.edit_add);
ETpin = (EditText)findViewById(R.id.edit_pn);
ETmail = (EditText)findViewById(R.id.edit_mail);
ETph = (EditText)findViewById(R.id.edit_ph);
Update = (Button)findViewById(R.id.update_btn);
progressDialog = new ProgressDialog(this);
Update.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.update_btn:
proUpdate();
break;
}
}
private void proUpdate(){
if (ETname.getText().toString().trim().equals("")){
ETname.setText(SharedPrefManager.getInstance(this).getName());
}
if (ETsurname.getText().toString().trim().equals("")){
ETsurname.setText(SharedPrefManager.getInstance(this).getSurname());
}
if (ETadd.getText().toString().trim().equals("")){
ETadd.setText(SharedPrefManager.getInstance(this).getAddress());
}
if (ETpin.getText().toString().trim().equals("")){
String pin = String.valueOf(SharedPrefManager.getInstance(this).getpin());
ETpin.setText(pin);
}
if (ETmail.getText().toString().trim().equals("")){
ETmail.setText(SharedPrefManager.getInstance(this).getUserEmail());
}
if (ETph.getText().toString().equals("")){
ETph.setText(SharedPrefManager.getInstance(this).getUserPhone());
}
String reg_name = ETname.getText().toString().trim();
String reg_surname = ETsurname.getText().toString().trim();
String reg_address = ETadd.getText().toString().trim();
String reg_pin = ETpin.getText().toString().trim();
String reg_mail = ETmail.getText().toString().trim();
String reg_phone = ETph.getText().toString().trim();
String old_mail = (SharedPrefManager.getInstance(this).getUserEmail());
int reg_id = (SharedPrefManager.getInstance(this).getid());
}
}
My SharedPrefManager
public class SharedPrefManager {
private static SharedPrefManager mInstance;
private static Context mCtx;
private static final String SHARED_PREF_NAME = "mysharedpref12";
private static final String KEY_USERNAME = "username";
private static final String KEY_USER_MAIL = "usermail";
private static final String KEY_USER_ID = "userid";
private static final String KEY_PHONE = "userphone";
private static final String KEY_NAME = "usename";
private static final String KEY_PIN = "pin";
private static final String KEY_SUR = "surname";
private static final String KEY_ADD = "address";
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
public boolean userLogin(int id, int pin, String phone, String username, String mail, String name, String surname, String address/**, String catagory*/){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_USER_ID, id);
editor.putInt(KEY_PIN, pin);
editor.putString(KEY_PHONE, phone);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_USER_MAIL, mail);
editor.putString(KEY_NAME, name);
editor.putString(KEY_SUR, surname);
editor.putString(KEY_ADD, address);
//editor.putString(KEY_CATA, catagory);
editor.apply();
return true;
}
public boolean isLoggedIn(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
if (sharedPreferences.getString(KEY_USERNAME, null) != null){
return true;
}
return false;
}
public boolean logOut(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
return true;
}
public int getid(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_USER_ID, Integer.parseInt(null));
}
public int getpin(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_PIN, Integer.parseInt(null));
}
public String getUsername(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null);
}
public String getUserEmail(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_MAIL, null);
}
public String getUserPhone(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null);
}
public String getName() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_NAME, null);
}
public String getSurname() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_SUR, null);
}
public String getAddress() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_ADD, null);
}
/**public String getcatagory() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_CATA, null);
}*/
}
Here's the code sample of what I was telling you.
private void proUpdate(){
...
else if (ETpin.getText().toString().equals("")){
string pin = String.valueOf(SharedPrefManager.getInstance(this).getpin());
ETpin.setText(pin);
}
...
}
For checking and placing text in all edittext at once:
private void proUpdate(){
if (ETname.getText().toString().trim().equals("")){
ETname.setText(SharedPrefManager.getInstance(this).getName());
}
if (ETsurname.getText().toString().trim().equals("")){
ETsurname.setText(SharedPrefManager.getInstance(this).getSurname());
}
if (ETadd.getText().toString().trim().equals("")){
ETadd.setText(SharedPrefManager.getInstance(this).getAddress());
}
if (ETph.getText().toString().equals("")){
ETph.setText(SharedPrefManager.getInstance(this).getUserPhone());
}
if (ETmail.getText().toString().trim().equals("")){
ETmail.setText(SharedPrefManager.getInstance(this).getUserEmail());
}
if (ETpin.getText().toString().equals("")){
string pin = String.valueOf(SharedPrefManager.getInstance(this).getpin());
ETpin.setText(pin);
}
updateMethodCall(); // your method call
}
This updateMethod will only be called when all the ediitexts are filled and you need not click submit button again.
Change following methods a bit like this.
public int getid(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_USER_ID, 0);
}
public int getpin(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_PIN,0);
}
I have been able to save Integers and Strings as Shared Preferences but have searched and cannot seem to be able to save a popup selected value as a shared preference? How to save Text View values in Shared Preferences, see my code below and let me know how to store to Shared Preferences and retrieve in onCreate(..)
MainActivity
cardViewlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, cardViewlist);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int demoCount = PreferenceHelper.setIntValue(MainActivity.this, PreferenceHelper.NAME_ANAOUNCE_TOTAL_TIME,Integer.parseInt(item.toString()));
Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
Log.d("asd", String.valueOf(demoCount));
textViewcount.setText(String.valueOf(demoCount));
return true;
}
});
popup.show();
}
});
Service:
final int count = PreferenceHelper.getIntValue(TTSService.this, PreferenceHelper.NAME_ANAOUNCE_TOTAL_TIME,1);
if (ConName != null) {
switch (count) {
case 1:
tts.speak(ConName1, TextToSpeech.QUEUE_FLUSH, null);
break;
case 2:
tts.speak(ConName2, TextToSpeech.QUEUE_FLUSH, null);
break;
case 3:
tts.speak(ConName3, TextToSpeech.QUEUE_FLUSH, null);
break;
case 4:
tts.speak(ConName4, TextToSpeech.QUEUE_FLUSH, null);
break;
case 5:
tts.speak(ConName5, TextToSpeech.QUEUE_FLUSH, null);
break;
}
}
PreferenceHelper:
public class PreferenceHelper {
public static String PREF_NAME="CallAnnouncer";
public static SharedPreferences AppPreference;
public static final String NAME_ANAOUNCE_TOTAL_TIME = "TotalTimeName";
public static String PREF_KEY_APP_LAUNCH_FIRST_TIME="IS_APP_FIRST_TIME";
public static String PREF_KEY_CALL_ENABLED="IS_INCOMING_ENABLED";
public static String PREF_KEY_SMS_ENABLED="IS_SMS_ENABLED";
public static String PREF_KEY_LANGUAGE="language";
public static String getValue(Context context, String key, String defaultValue){
AppPreference=context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
String str=AppPreference.getString(key,defaultValue);
return str;
}
public static void setValue(Context context, String key, String value){
AppPreference=context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = AppPreference.edit();
editor.putString(key,value);
editor.commit();
}
public static String setValueLan(Context context, String key, Locale locale){
AppPreference=context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = AppPreference.edit();
editor.putString(key,locale.toString());
editor.commit();
return key;
}
public static String getValueLan(Context context, String key, Locale locale){
AppPreference=context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
String str=AppPreference.getString(key,locale.getDisplayLanguage());
return str;
}
public static boolean contains(Context context, String key){
AppPreference=context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
if(AppPreference.contains(key)){
return true;
}else{
return false;
}
}
public static void clearPreference(Context context){
AppPreference=context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
AppPreference.edit().clear().commit();
}
public static int getIntValue(Context context, String key, int Value) {
AppPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
int str = AppPreference.getInt(key, Value);
return str;
}
public static int setIntValue(Context context, String key, int value) {
AppPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = AppPreference.edit();
editor.putInt(key, value);
editor.commit();
return value;
}
}
I am creating an app which supports Multiple Themes. The Current implementation is that the user can select a theme from two themes & the selected theme is applied.
But now i need to add more themes. I have added some themes in the xml file. But i don't know how to handle it in the Java file below.
So please guide me. Thanks in Advance!
Preferences.java
public class Preferences {
private static final BoolToStringPref[] PREF_MIGRATION = new BoolToStringPref[]{
new BoolToStringPref(R.string.pref_dark_theme, false,
R.string.pref_theme, R.string.pref_theme_value_red),
};
public static void sync(PreferenceManager preferenceManager) {
Map<String, ?> map = preferenceManager.getSharedPreferences().getAll();
for (String key : map.keySet()) {
sync(preferenceManager, key);
}
}
public static void sync(PreferenceManager preferenceManager, String key) {
Preference pref = preferenceManager.findPreference(key);
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry());
}
}
/**
* Migrate from boolean preferences to string preferences. Should be called only once
* when application is relaunched.
* If boolean preference has been set before, and value is not default, migrate to the new
* corresponding string value
* If boolean preference has been set before, but value is default, simply remove it
* #param context application context
* TODO remove once all users migrated
*/
public static void migrate(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
for (BoolToStringPref pref : PREF_MIGRATION) {
if (pref.isChanged(context, sp)) {
editor.putString(context.getString(pref.newKey), context.getString(pref.newValue));
}
if (pref.hasOldValue(context, sp)) {
editor.remove(context.getString(pref.oldKey));
}
}
editor.apply();
}
public static void applyTheme(ContextThemeWrapper contextThemeWrapper) {
if (Preferences.darkThemeEnabled(contextThemeWrapper)) {
contextThemeWrapper.setTheme(R.style.AppTheme_Blue);
}
}
private static boolean darkThemeEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.pref_theme),
context.getString(R.string.pref_theme_value_red))
.equals(context.getString(R.string.pref_theme_value_blue));
}
private static class BoolToStringPref {
private final int oldKey;
private final boolean oldDefault;
private final int newKey;
private final int newValue;
private BoolToStringPref(#StringRes int oldKey, boolean oldDefault,
#StringRes int newKey, #StringRes int newValue) {
this.oldKey = oldKey;
this.oldDefault = oldDefault;
this.newKey = newKey;
this.newValue = newValue;
}
private boolean isChanged(Context context, SharedPreferences sp) {
return hasOldValue(context, sp) &&
sp.getBoolean(context.getString(oldKey), oldDefault) != oldDefault;
}
private boolean hasOldValue(Context context, SharedPreferences sp) {
return sp.contains(context.getString(oldKey));
}
}
}
SettingsActivity
protected void onCreate(Bundle savedInstanceState) {
Preferences.applyTheme(this);
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setToolbar();
addPreferencesFromResource(R.xml.preferences);
Preferences.sync(getPreferenceManager());
mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preferences.sync(getPreferenceManager(), key);
if (key.equals(getString(R.string.pref_theme))) {
finish();
final Intent intent = IntentCompat.makeMainActivity(new ComponentName(
SettingsActivity.this, MainActivity.class));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
};
}
Here is a blog post outlining how to do this (with source available)
http://www.hidroh.com/2015/02/25/support-multiple-themes-android-app-part-2/
Here is a guide that shows you how to programmatically quickly switch via user input (button presses, etc.) (The above that extends PreferenceFragment is probably more ideal, but could be informative to read below too)
http://www.developer.com/ws/android/changing-your-android-apps-theme-dynamically.html