cannot get right result from getdefaultsharedpreferences - java

When I use defaultsharedpreferences to save multiple data, I found data is covered. I feel confused about what happened. The expected values from preferences
userId is 2
authorizedHeader is bhlrYXZpbjpseWthdmlu
and retrieved values
userId is 2
authorizedHeader is 2
private static final String PREF_AUTHORIZED_QUERY = null;
private static final String PREF_USERID_QUERY = null;
public static String getStoredUserIdQuery(Context context){
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_USERID_QUERY, null);
}
public static String getStoredAuthorizedQuery(Context context){
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_AUTHORIZED_QUERY, null);
}
public static void setStoredQuery(Context context, String userId, String authorizedHeader){
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_AUTHORIZED_QUERY, authorizedHeader)
.putString(PREF_USERID_QUERY, userId)
.apply();
}

you are using values as null for both keys mean there is only one key i.e. null which will override the each other (PREF_USERID_QUERY will over write previous values which were saved with null as key)
so give them values
private static final String PREF_AUTHORIZED_QUERY = "authorized";
private static final String PREF_USERID_QUERY = "userid";
You can imagine it like
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString("null", authorizedHeader)
.putString("null", userId) // so there is actually only one key
.apply();

Related

Android colors in sharedpreferences

In my application is settings_activity where people can change some colors (icons, text etc). I want to put colors in sharedpreferences, created class:
public class AppData {
static SharedPreferences prefdata;
static SharedPreferences.Editor editordata;
static final String FCOLOR_KEY = "#FFFFFF"; //first color
static final String SCOLOR_KEY = "#FFFFFF"; //second color
static final String TCOLOR_KEY = "#FFFFFF"; //text color
static final String ICOLOR_KEY = "#FFFFFF"; //icon color
static final Image BIMG_KEY = null; //bakcground image
}
What is best value type for colors (int, string or just colors)?
How can I change values from appdata by use settings_activity and how can I use it (colors) in xml files? Should I use colors.xml(how?)?
If you are going to use the color enumeration, I would just use an int to store it. (See below for data type of ints)
http://developer.android.com/reference/android/graphics/Color.html
However, if you are going to use the hexadecimal value, then I would store it as a string. When you load your app, check the shared preferences and load the string and if the option does not exist load a default color.
object.setColor(sharedPreferences.getString("COLOR", "#FFFFFF"));.
if the user give you hex string ( as you answer to NoChinDeluxe)
you should store it in string in your sharePref and then parse it with :
public static int parseColor (String colorString)
I always do my Prefs like this:
private static final String KEY_COLOR_1 = "color 1";
private static Prefs instance;
public static Prefs with(Context ctx) {
if (instance == null) {
instance = new Prefs();
}
instance.ctx = ctx.getApplicationContext();
return instance;
}
private Context ctx;
private Prefs() {
}
public SharedPreferences getPrefs() {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public String getColor1() {
return getPrefs().getStrings(KEY_COLOR_1, "");
}
public void setColor1(String color) {
getPrefs().edit().putStrings(KEY_COLOR_1, color).apply();
}
and then you can get your color with:
Pref.with(this).getColor1();

Failed to get sharedPreferences value

I want to get a value from sharedPreferences. I put the sharedPreferences on Config.java
public static final String SHARED_PREF_NAME = "myauthapp";
public static final String EMAIL_SHARED_PREF = "email";
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
public static final String REGISTER_URL = "http://192.168.1.6/db_android_native/register.php";
And I try to get the value of REGISTER_URL on Register.java with this
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String RREGISTER_URL = sharedPreferences.getString(Config.REGISTER_URL, "Not Available");
And it's always return Not Available
Why it's not give me the value of Register_URL on Config.java ?
If you need the link stored by REGISTER_URL in Config.java, you should just simply get it with
String url = Config.REGISTER_URL;
Your code
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String RREGISTER_URL = sharedPreferences.getString(Config.REGISTER_URL, "Not Available");
looks for a preference with name provided by Config.REGISTER_URL, but it is not a good idea storing preferences with such a long and complex name. The getSring method returns it's provided default value until you have not saved any preference with that name like this:
sharedPreferences.edit().putString(prefname, value).apply();

I'm using shared prefrences to store a Location value received from gps, How can i retrive the same from the getAppData()?

public class StorageHelper {
public static final String PREFS_NAME = "LOCATION_DATA";
public static void saveAppData(Context ctx, String key, Location value){
SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
String lat =Double.toString(value.getLatitude());
String lon=Double.toString(value.getLongitude());
Set location = new HashSet();
location.add(lat);
location.add(lon);
editor.putStringSet(key,location);
editor.apply();
}
public static String getAppData(Context ctx, String key){
SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
return settings.getStringSet(key,);
}
}
what is the second argument to pass in the return settings.getStringSet()?
I am expected to send a java.lang parameter , but a Set is of java.utiity type.
As said in documentation, second parameter is value that returns if there is no object associated with used key value. You can use empty set or null, but after call this method you should check for not null value.

How can I retrieve Value of SharedPreference file in another Activity?

Activity 1st..
Here this is my first activity to add data
preferences=PreferenceManager.getDefaultSharedPreferences(context);
preferences = getPreferences(MODE_PRIVATE);
editor = preferences.edit();
editor.putString("userid",et_username.getText().toString());//adduserid
editor.putString("password",et_password.getText().toString());//add password
editor.commit();
Activity 2nd
This is my second activity to retrieve data.
String userName=preferences.getString("userid","");
String password=preferences.getString("password","");
Log.d("user : second", ""+preferences.getString("userid",""));
Log.d("password : second", ""+preferences.getString("password",""));
Here Log is not displayed because of null value.
Check your preferences object (probably is null). That might be the problem, as the other String variables are never null, the can be empty string ("").
Are you missing the initialization of preferences in the second Activity just in this example?
String userName=preferences.getString("userid");
String password=preferences.getString("password");
Log.d("user : second", ""+userName);
Log.d("password : second", ""+password);
Could you please try this way.
In both activities just use this to get the SharedPreferences object:
SharedPreferences prefs = getSharedPreferences("PREFS", Context.MODE_PRIVATE);
It may be that you attempt to access different preferences files from different Activities.
Or just use
PreferenceManager.getDefaultSharedPreferences(this);
i just store the one integer value you must more then one value in it..
PreferenceConnector.writeInteger(home.this, PreferenceConnector.com_id, homeComp_id);
below the preferenceConnector class to be use in it...
public class PreferenceConnector {
public static final String PREF_NAME = "Shared Preference";
public static final int MODE = Context.MODE_PRIVATE;
public static final String com_id = "com_id";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key, boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
and then u also use the share preference value to other activity like below...
int Pref = PreferenceConnector.readInteger(mainpage.this, PreferenceConnector.com_id, 0);
hope above code to be useful...

How to find a static String in a Interface

I have the folowing interface;
public static interface Attributes
{
public final static String InterestDeterminationDate = "InterestDeterminationDate";
public final static String CreditType = "CreditType";
public final static String NumberInternal = "NumberInternal";
public final static String InterestRate = "InterestRate";
public final static String RemainingDebtAmount = "RemainingDebtAmount";
public final static String ConsumerPart = "ConsumerPart";
public final static String TechnicalProductName = "TechnicalProductName";
public final static String TermOfDuration = "TermOfDuration";
public final static String PeriodInterestTaxReduction = "PeriodInterestTaxReduction";
public final static String OriginMark = "OriginMark";
public final static String Currency = "Currency";
public final static String PenaltyRuleId = "PenaltyRuleId";
public final static String InstallmentCalculationMethod = "InstallmentCalculationMethod";
public final static String InterestRenewalDate = "InterestRenewalDate";
public final static String TechnicalProductDescription = "TechnicalProductDescription";
public final static String TechnicalProductDate = "TechnicalProductDate";
public final static String CollectionIntervalPeriod = "CollectionIntervalPeriod";
public final static String Enddate = "Enddate";
}
I need to check is a given string is a part of this Attributes Interface.
How can i check this?
Regards,
bas Hendriks
If you really want todo this, then you should use reflection and go through all the values in Attributes.
A better way to do this would be the use of enums :
public enum Attributes{
InterestDeterminationDate,
CreditType,
NumberInternal,
InterestRate,
RemainingDebtAmount,
ConsumerPart,
TechnicalProductName,
TermOfDuration,
PeriodInterestTaxReduction,
OriginMark,
Currency,
PenaltyRuleId,
InstallmentCalculationMethod,
InterestRenewalDate,
TechnicalProductDescription,
TechnicalProductDate,
CollectionIntervalPeriod,
Enddate;
}
and the Attributes.valueOf(yourVariable); would check this for you.
Beware with enum, the valueOf() method will throw a IllegalArgumentException if yourVariable isn't in Attributes. Plus you yourVariable isn't null or you will have to handle a NullPointerException
Your question doesn't make it clear whether you're trying to find out if the query string is the property name or value. If you're trying to find out if it's a value, the following will work:
public static boolean hasValue(String value) throws IllegalAccessException {
for(Field field : Attributes.class.getDeclaredFields()) {
if(((String)field.get(Attributes.class)).equals(value)) {
return true;
}
}
return false;
}
However, I would advise following Colin's suggestion of using an Enum, it will be easier for you to work with in the future.
You can build a set using reflection and test against that set:
Class<Attributes> attr = Attributes.class;
Field[] fields = attr.getDeclaredFields();
final Set<String> fieldsInAttributes = new HashSet<String>();
for (Field field : fields) {
fieldsInAttributes.add(field.getName());
}
System.out.println(fieldsInAttributes.contains("PenaltyRuleId"));
You can use the reflection API, and the "getFields()" method of the Class class.
Then you check the field name with the "getName()" method of the Field class.
Here is the Oracle official tutorial.
public static String getFieldName(String fieldValue) throws Exception {
for (Field field : Attributes.class.getFields())
if (fieldValue.equals(field.get(null)))
return field.getName();
return null;
}

Categories