开发者

In android how to search that sharedpreference contains some value or not?

In android how to search that sharedpreference contains some value or not?

Actually I m making application which takes password and confirm password as fields.when user start app for first time he must enter both password and confirm password. But i want when user restart that app he must ask to enter only password.

For that i store password in sharedPreferences but now how do i know that their is already password exists in sharedPreferences or not?

so that if their is no password in sharedPreferences i can show the activity which contains bot开发者_运维问答h password and confirm password to enter AND if there exists password then i wl show activity that contains only password to enter.

If Anyone have idea then please help me.I m tring from many days but still not getting the output.


You can check it by using the contains method on your SharedPreferences instance:

boolean hasPassword = preference.contains("passwordKey");

API Docs:

public abstract boolean contains (String key) 

Since: API Level 1
Checks whether the preferences contains a preference.

Parameters
key The name of the preference to check.

Returns
Returns true if the preference exists in the preferences, otherwise false.


for saving data...

 SharedPreferences settings = getSharedPreferences("YourKey", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("password", passwordValue);        
     // Don't forget to commit your edits!!!
    editor.commit();

for retrieving...

 SharedPreferences settings =this.getSharedPreferences("YourKey", 0);
    String userData = settings.getString("password", "0");

    if((userData.equals("0"))){
        //password has not been saved...
    }
    else{
           //password is already there...
    }


fist check if passwort is set:

boolean password_exists = !settings.getString("password","").equals("");

then hide or show the field for the second password

second_passwort_edittext.setVisibility(password_exists ? View.GONE:View.VISIBLE);

After entering the password you can change the behaviour with password_exists (compare the passwords and set them if false, compare with given stored password if true)


I think that you could just validate if you have received something by getting the password value from your shared preferences

if(preferences.getInt("storedPass", 0) != null) {
    //Do Stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜