In my onCreate() I have:
if(sharedPref.getString("name",null)==""){EditText.setText("Something");}
else{EditText.setText(sharedPref.getString("name",null));}
And then in my onStop() I have:
sharedPrefEditor.putString("name",EditText.getText().toString());
The EditText shows only the hint when I first install and run it. It does seems to display the correct text when it's started later, however.
Don't use == to compare content of Strings. Use equals() instead :
if(sharedPref.getString("name",null).equals("")){
EditText.setText("Something");
}
Why should I use equals instead of ==
First of all you are not using correctly the shared preferences. You are typing null as second parameter which is the value you will get if the key you typed as first parameter is not defined. This is not a problem itself but then in your if sentence you are comparing it to an empty string.
So first of all use equals instead of ==and then if you want to receive an empty string if the key is not defined type an empty string as second parameter of SharedPreferences.gerString method.
Hope it helps ;)
If "Something" is to be used if preference not set, then:
EditText.setText(sharedPref.getString("name","Something"));
getString() will automatically return "Something" if preference is not set. No need of extra code.
String strName = sharedPref.getString("name","");
if(!strName.isEmpty()){
EditText.setText(strName);
}else{
EditText.setText("Something");
}
The operator == can not be used to compare strings in Java.
if(string1.equals(string2){
}
Also, you set a value to SharedPreferences, but you never commit the changes.
sharedPrefEditor.commit();
OnCreate
String prefsVal = sharedPref.getString("name", null);
if(prefsVal.equals(null)){ //If default value was returned
EditText.setText("Something");
}else{
EditText.setText(prefsVal);
}
OR
The following will turn your posted code into a single line solution. The second parameter passed to SharedPref is the default value to be returned if no vale was found for the given key.
EditText.setText(sharedPref.getString("name", "Something");
OnStop
sharedPrefEditor.putString("name", EditText.getText().toString());
sharedPrefEditoy.commit();
Related
I am passing data from one activity to another but if I print the data in the other activity, it shows null.
I used PutExtra and GetExtra.
in first acticity
intent.putExtra(pin,pins);
System.out.println(pin);
In second Activity
Intent intent = getIntent();
pined=intent.getStringExtra("pins");
System.out.println(pined);
I got a null message when I try to print the data
2019-09-05 08:59:09.425 26480-26480/com.example.beachbocI/System.out: null
In the first activity
intent.putExtra("pin",pins);
System.out.println(pin);
In the second activity
pined=getIntent().getStringExtra("pin");
System.out.println(pined);
It shoud be like this
intent.putExtra("pin",pins);
//"pin" means the name of string
//pins means your value
To pass value you should write below
intent.putExtra("pins",pin); //here `pins` is key use it to get your desired value
to get your desired value use the same key as below
intent.getStringExtra("pins"); // use same key `pins`
So putExtra has two params, 1st is a key, second value
pin should be String key object
getStringExtra has one param, it takes a String key value, which should be pin
I use this function to extract shared preferences from Android App. However, I am not sure if the requested field exists. Should I wrap the code inside try catch or getString() is safe when the field does not exist?
public String loadPreferences(String what){
SharedPreferences settings =this.getSharedPreferences("settings", Context.MODE_PRIVATE);
String content =settings.getString(what, "empty");
return content;
}
If by "field", you mean the value keyed by whatever what is, getString() will not return null in your code snippet. It will return the value keyed by whatever what is, or "empty" if there is no value for that preference.
You should read documentation of getString here, it clearly says,
Returns the preference value if it exists, or defValue. Throws
ClassCastException if there is a preference with this name that is not
a String. This value may be null.
In your case, defValue is "empty"
So exception is possible only when value you are trying to return is not of specified type, it should never be the case of getString() though
If you search through this link : https://developer.android.com/reference/android/content/SharedPreferences.html
You will find this method :
getString(String key, String defValue)
Which means if you havnt stored anything in SharedPreferences with this key and you are trying to get value for this key than it will return default value
So in your case
String content =settings.getString(what, "empty");
For what key if you havnt stored anything with this key and if you are trying to get its value than it will return default value that is "empty" in your case
I have a problem with setText(). Although there were many questions about this issue, no single answer solved my problem..
I have one city name saved with SharedPreferences. I get city successfully from SharedPreferences. I want to do the following textview.setText(city) [of course, firstly I determine the textview with findbyId-proper, existing id ]. This is done in onResume() method.
Than I use getText() and System.out.println(getText()) shows exactly the right, saved city. The UI shows the text which was defined at the XML layout of the activity.
I have no idea what to do and how is this even possible. I do not get any errors.
Please, help.
In onResume() method right after super.onResume(); :
city=settings.getString("savedLocation", "null");
textView.setText(city);
System.out.println(city + " " textView.getText());
textView.getText() returns not text string, but object. You should use textView().getText().toString() to retrieve text from a text view
I have two spinners in my app. I want that if i select option "first" from spinner 1 and option "second" from spinner 2, then the action gets performed. But it show "NUMBERFORMATEXCEPTION".
Here's the code
if (((spinner.getItemAtPosition(pos).toString()=="first" &&
(s2.getItemAtPosition(id).toString()=="second"))))
{
tv.setText(String.valueOf(gmtomilli(x)));
}
This code has the error, if i omit this code, then the app works fine,without action
Do String comparison using equals.
spinner.getItemAtPosition(pos).toString()=="first"
instead use:
spinner.getItemAtPosition(pos).toString().equals("first")
Similarly for:
s2.getItemAtPosition(id).toString()=="second"
instead use:
s2.getItemAtPosition(id).toString().equals("second")
Read this for more information.
== compares references,not the values. In your case, you want to check for the value equality, not the reference equality.
EDIT:
Since you have mentioned that your code is generating NumberFormatException, I probably believe that either pos or id are of String type generating the NumberFormatException.
EDIT 2:
As per the your comment:
float x=Float.parseFloat(String.valueOf(et.getText()));
Your getText() is returning a String that can't be actually parsed into a float. Try checking if the content is actually a float in String format.
Besides, use String.trim() before parsing to ensure your String doesn't contain any leading or trailing whitespaces that's generating the NumberFormatException.
I want to compare 2 strings.
My first value is in 'list[0][0]' variable and the second value is in item[0].
But when I am comparing the 2 strings using 'if' statement, I don't get the answer.
if(selected_list[0][0]==items[0])
{
// some code
}
it is not working.
But when I am hard-coded these values, it is working fine.
if("banana"=="banana")
{
// some code
}
Please give me the solution?
Thank you..
Here is an explanation of how strings should be compared and the different options for doing so. They aren't as simple as comparing int's.
if (string1.equals(string2))
You have to compare it as [list[0][0] isEqualToString:items[0]] otherwise you are comparing their addresses not the values.
Use the compareTo() or equals() method of one of your strings, passing the other string as argument.
string1.equals(string2)
// returns true if both strings are equal
string1.compareTo(string2)
// returns 0 if both strings are equal