I am using Shared preferences for the first time and getting errors.
my code is like this :
public class MainActivity extends Activity {
static final String ONE = "";
static final String TWO = "";
private static SharedPreferences mSharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences.Editor edi = mSharedPreferences.edit();
edi.putString(ONE, "1");
edi.putString(TWO, "2");
edi.commit();
String one = mSharedPreferences.getString(ONE,"1");
String two = mSharedPreferences.getString(TWO,"2");
System.out.println("Your Numbers: "one+ " " + two);
}
}
Expected Output:
Your Numbers: 1 2
Console Output:
Your Numbers: 2 2
I can't figure out what i am doing wrong in it. Share your views.
You need to add some string to the names/keys. Currently both key names are blank and hence your code is overwriting the same preference value
.
Change the static strings as follows and it should work fine.
static final String ONE = "one";
static final String TWO = "two";
Also try using a helper class to make things simpler with shared preferences. Here is one that i wrote: Android-SharedPreferences-Helper
Because of this:
static final String ONE = "";
static final String TWO = "";
change it to:
static final String ONE = "One";
static final String TWO = "Two";
U need unique values for every preference.
In your case the ONE gets overridden by the TWO.
Extra info
If u look in the android docs here you will see that putString requires two parameters:
key : String: The name of the preference to modify.
value : String: The new value for the preference.
and if u than look at getString here you will notice that it also has two parameters, both the same as putString:
key : String: The name of the preference to retrieve. -- important
defValue : String: Value to return if this preference does not exist.
The name/key is the part that let the get part know from which preference it needs to get the value.
Hope this will make things a bit clearer for u!
Both the strings are empty
static final String ONE = "";
static final String TWO = "";
It should be like :
static final String ONE = "one";
static final String TWO = "two";
Related
Having a little trouble figuring this one out. I have two values stored in my Config class as shared preferences, an email address and a URL. This will parse JSON to a ListView from my server. I'm trying to concatenate them together but it is not working.
Config.java
public class Config {
//URL to JSON API
public static final String GET_ORDERS_URL = "http://192.568.8.245/android/json3.php?user_email=";
//Storing current user
public static final String EMAIL_SHARED_PREF = "user_email";
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Concatenated URL to JSON API
private static final String baseurl = Config.GET_ORDERS_URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Fetching email from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String user_email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available");
//Concatenated JSON API URL
String url = baseurl + user_email;
//Initializing Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setTitle(user_email);
}
I know user_email is being stored because I am calling it within MainActivity and setting the title of my toolbar with it. Replacing user_email with an actual email results in success, obviously I don't want to do that. Any idea what I need to do?
use android UrlEncoder class to make correct url
this is the best way. Using manual concatenate can result in malformed requests.
and also you can build URI like this
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
Get the values and call concatStrings(str1,str2);
Use something like this
String concatStrings(String string1,String string2){
StringBuilder strBuilder=new StringBuilder();
strBuilder.append(string1);
strBuilder.append(string2);
return strBuilder.toString();
}
Note: the OP has applied this answer already to the code in it's question. It was meant for version 1 of the question.
The concatenation is working and results in the string:
"http://192.568.8.245/android/json3.php?user_email=user_email"
because you concatenate with the shared preferences key, not the value.
You want to concatenate with the value retrieved from shared preferences instead
String user_email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF);
String url = Config.GET_ORDERS_URL + user_email;
I have a doubt related with tag. For example, if i have a button with a tag "ButtonTag". Tag is a object, but i would like to catch a string "ButtonTag" and use inside a switch. Summing up, to get a String of Object tag and to use in a Switch. Is possible ?
public void ArtGeneralButton(View view){
selsub = view.getId();
tagsub = view.getTag(); \\ Object -> String How???
// String myString = getString(null,tagsub,);
UpdateAnsList myUpdate = new UpdateAnsList(this);
myUpdate.StartUpdateAnsList(selsub,tagsub);
}
String tagString = (String) view.getTag();
It's as simple as that as long as whatever was originally used to set the tag was a String
As for using a String in a switch is concerned, I prefer to use int as the key for a switch. In this case I'd set the tags as ints - either arbitrary values such as 1, 2, 3 etc or use the resource ids of strings in the strings.xml file.
why on all demos and tutorials in SQLiteOpenHelper class variables are always: public static final
Have a look:
public static final String ORDER_ID = "order_id";
public static final String ORDER_LOGIN_NAME = "login_name";
public static final String ORDER_RESTO_U_NAME = "resto_uniqe_name";
My question is: I am making an application and its database is too big. So, I will have to make atleast 60-70 variables of these kind. Won't it affect application performance? As these are static variables.
Any help will be highly appreciated....
Well, whether they public or private or package-protected depends on your needs, but final static is a good way of declaring constants per Android guidelines, take a look here for explanation: http://developer.android.com/training/articles/perf-tips.html#UseFinal
Consider the following declaration at the top of a class:
static int intVal = 42;
static String strVal = "Hello, world!";
The compiler generates a class initializer method, called , that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups.
We can improve matters with the "final" keyword:
static final int intVal = 42;
static final String strVal = "Hello, world!";
The class no longer requires a method, because the constants go into static field initializers in the dex file. Code that refers to intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup.
I am trying to define a search string and new to android, not sure how to do the same. Any clue?
Here's my code for the same:
public final static String PROD_ENVIRONMENT = "https://mobile13.com/fwd/answers/answers/service/v1/?q=**KEYWORD**%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
I want to replace the KEYWORD with a dynamic string like %s, which can be recognized with a static string say "public static string KEYWORD" , which i can check ,in turn matches the typed keyword and display the results accordingly
Try this
public final static String PROD_ENVIRONMENT = "https://mobile13.com/fwd/answers/answers/service/v1/?q="+KEYWORD+"%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
That is if you have the static variable in the same class. If you have it in a different class, say StaticUtils class then you can put it as StaticUtils.KEYWORD.
why will String.format not work?
android documentation
I am using following source https://github.com/liveservices/LiveSDK-for-Android.
Do someone know how to get shared preferences after the LiveAuthClient process. I have to get
REFRESH_TOKEN_KEY and COOKIE_DELIMITER from the sharedprefences file and clear it after saving it in a database. The aim is to save this to values in a database to login with multiple skydrive accounts.
Any ideas would be helpful. Thank you.
If Someone wants to know use:
/** Name of the preference file */
public static final String FILE_NAME = "com.microsoft.live";
public static final String COOKIES_KEY = "cookies";
public static final String REFRESH_TOKEN_KEY = "refresh_token";
SharedPreferences preferences = getSharedPreferences(SDriveConstants.FILE_NAME, Context.MODE_PRIVATE);
String refresh_tkn_key = preferences.getString(SDriveConstants.REFRESH_TOKEN_KEY, "");
String cookies_key = preferences.getString(SDriveConstants.COOKIES_KEY, "");