I move from Activity A to Activity B by intent.I am storing some values in shared preferences in Activity B.In activity A oncreate() i am fetching the values of the shared preferences to compare with some conditions however it gives me null pointer exception as expected (As i do not go to Activity B).However i want to write a condition to fetch the data from shared preferences if the value is not null.Can some one please say how can i achieve this? Following is my code:
In Activity B:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MerchantLogin.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("showdialog_login", "dontshow");
editor.commit();
In Activity A:
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences prefs =null;
prefs = PreferenceManager.getDefaultSharedPreferences(LoginScreen.this);
SharedPreferences.Editor editor = prefs.edit();
if ((prefs.getString("showdialog_login", null).equalsIgnoreCase("dontshow")))
{
}
else if((prefs.getString("showdialog_login", null).equalsIgnoreCase("true")))
{
}
else if((prefs.getString("showdialog_login", null).equalsIgnoreCase("dummy")))
{
}
else
{
editor.putString("showdialog_login", "false");
editor.commit();
}
}
However i get error at this line:
if ((prefs.getString("showdialog_login", null).equalsIgnoreCase("dontshow"))).How can i execute this block of code.
Instead of :
prefs.getString("showdialog_login", null)
Use:
prefs.getString("showdialog_login", "")
Because, if value for "showdialog_login" preference is not set, it will return null value and you might get NPE (Null pointer exception).
You should always use the constant as the first argument when comparing using equals, i.e.
"dontshow".equalsIgnoreCase(prefs.getString("showdialog_login", null))
You are getting the NullPointerException because the showdialog_login property is not yet set, i.e.
prefs.getString("showdialog_login", null)
returns null, because that's what you set the default value to.
Effectively, your condition is thus
null.equalsIgnoreCase("dontshow")
-which naturally ends up in a NullPointerException.
In Activity A:
static SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState)
{
prefs = getSharedPreferences("showdialog_login",0);
String ss= prefs.getString("showdialog_login", "default");
if ((ss.equalsIgnoreCase("dontshow")))
{
}
else if((ss.equalsIgnoreCase("true")))
{
}
else if((ss.equalsIgnoreCase("dummy")))
{
}
else
{
editor.putString("showdialog_login", "false");
editor.commit();
}
}
Related
This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 4 years ago.
How can I use SharedPreferences on Android Studio to save some data like the value of a boolean?
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
editor.putBoolean("firststart",false);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
boolean firstStart= prefs.getBoolean("firststart",false);
if (!firstStart) {
Intent intent12 = new Intent(getApplicationContext(),FirstStart.class);
startActivity(intent12);
prefs.getBoolean("firststart",true);
}
else if (firstStart) {
}
If I use this code everytime I create the activity the value of the boolean return false and then true.
How can I resolve this problem and don't lose the data?
You do not need to save false as value everytime , simply if there is no value, you get false here prefs.getBoolean("firststart",false) otherwise true as your saved value
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
boolean firstStart= prefs.getBoolean("firststart",false);
if (!firstStart) {
// save true during first time initialization
Intent intent12 = new Intent(getApplicationContext(),FirstStart.class);
startActivity(intent12);
editor.putBoolean("firststart",true);
editor.apply();
} // for second run, when you get true
else if (firstStart) {
}
well actually your code is resetting itself on each onCreate so what you have to do is something like this
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firststart", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firststart", false).commit();
}
}
}
hope this helps
I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
I try call SharedPreferences, and I pass a parameters but not work (not update and not put data)
I don't know I do wrong?
public void put(String value){
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
editor.putString("isFirstRunCheck", value);
editor.commit();
}
public void checkFirstRun3(){
SharedPreferences prefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
String name ="";
if (restoredText != null) {
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
}
if(name.equals("true")){
Toast.makeText(getActivity(), "click si ", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "click no ", Toast.LENGTH_SHORT).show();
}
}
I put my "put()" I do not see it work
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
cbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
}
});
I'm not sure why you don't think this is working, but I'm guessing it is because your code doesn't do what you think it does.
First of all, the comment on this line is wrong:
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
The second parameter to getString() is the default value- in this case you are specify that the default value should be an empty string if you have not previously saved a value to the "isFirstRunCheck" key.
Second, you seem to be expecting a value of "si". However, you are only ever calling put("true") and put("false")- you never call put("si"), so your conditional in checkFirstRun3() will always be false.
As an aside, a String is an odd way to save boolean data. SharedPreferences has a getBoolean() and a putBoolean() that will likely suit your needs better.
Try to change
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
to
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor spe = sp.edit();
Use
spe.putString("yourStringKey", yourStringValue).commit()
and then get your data using the "yourStringKey"
and don't forget to call your put(someData) method.
I've created a class to save some username and password using the Android SharedPreferences, its seems that the methods for set both username and password are ok.
But everytime i try to get these, from within another activity or by just trying to print out the value i receiver nothing (if trying to print the value) or null (if trying to get on i activity).
Here is my code:
public class AuthPreferences {
private static final String KEY_USER = "userid";
private static final String KEY_PASSWORD = "mypassword";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
Log.v("MailApp", "User is " + user);
editor.apply();
if(editor.commit() == true) {
System.out.println("The user was set!");
}else{
System.out.println("The user was not set!");
}
}
public void setPassword(String pass) {
Editor editor = preferences.edit();
editor.putString(KEY_PASSWORD, pass);
Log.v("MailApp", "Password is " + pass);
editor.apply();
if(editor.commit() == true) {
System.out.println("The password was set!");
String mainUser = preferences.getString(KEY_PASSWORD, "456");
System.out.println(mainUser);
}else{
System.out.println("The password was not set!");
}
}
public String getUser() {
return preferences.getString(KEY_USER, "456");
}
public String getPassword() {
return preferences.getString(KEY_PASSWORD, "456");
}
Here is how i'm trying to get it:
preferences = new AuthPreferences(getActivity());
try {
String mainUser = preferences.getUser();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("App", "Could not get the user");
}
It is all because you use Activity as a context (you use result of getActivity() method as context). Since you got different activities you got different contexts so in result you are accessing different shared preferences files (XMLs). In other words you are writing to file A in activity A, and then read in activity B using file B as your source. This obviously is not going to work. To have this all work as you expect you shall always use the same context for data that you want to be accessed across many activities, in this case I recommend to use Application context. Technically, instead of calling getActivity() to get context in your fragment, you call getActivity().getApplicationContext() to get your application context, so you will be accessing the same shared preferences storage file, not matter what activity or fragment is doing that write or read.
Aside from this there's no need to call apply() and commit() as these two is kinda equivalent and do the same. Please check docs for more information.
Try replacing:
Editor editor = preferences.edit();
with
SharedPreferences.Editor editor = preferences.edit();
Then replace editor.apply(); with editor.commit();.
Instead of doing:
editor.apply();
do this:
editor.commit();
Also you need to commit your edits by using the methods somewhere:
AuthPreferences preferences = new AuthPreferences(getActivity());
preferences.setUser("USER_NAME");
preferences.setPassword("PASSWORD_VALUE");
I have in preferences.xml following EditTextPreference:
<EditTextPreference
android:name="#string/pref_test"
android:defaultValue="0.6"
android:inputType="numberDecimal"
android:key="editTestPref"
android:maxLength="5"
android:summary=""
android:title="#string/pref_test" />
In one of my activities I read the value.
But the problem is if the user enters nothing (""), my app crashes. Sure I could do a if statement in the activity to check if its empty string, but I want to do following:
In Preferences.java I get changes of the preferenceEditText. There I want to set a default value if the user enters "":
if (preference.getKey().equals("editTestPref")) {
if(newValue.equals(""))
{
final SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("editTestPref", "1");
prefsEditor.commit();
summary = "0.6"; // to update the summary of preference
}
else
{
summary= (String) newValue;
}
}
I also tried this code:
SharedPreferences customSharedPreference = getSharedPreferences(
"myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference
.edit();
editor.putString("editTestPref", "1");
editor.commit();
Both do not work, they do not update the sharedPreference value. It is still "".
Implement SharedPreferences.OnSharedPreferenceChangeListener like so:
public class YourPrefsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
// ... your existing code ...
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set up a listener whenever a key changes
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ("editTestPref".equals(key)) {
String val = sharedPreferences.getString("editTestPref", "");
if (val == null || val.trim().equals("")) {
val = "0.6"; // <-- your default value
sharedPreferences.edit().putString(key, val).commit();
}
}
}
}
The method is called when the user changed the preferences value, and checks if he entered an empty string. If so, the value is replaced by your default value.
You should rather use if(newValue.isEmpty()) instead of checking the characters
i dont see anything wrong in your code but try this if it works..
Replace this
prefsEditor.putString("editTestPref", "1");
with
prefsEditor.putString("editTestPref", String.valueof(1));
Best Luck.