set and store password in android apps - android

I have try to set and store the password for my apps, but it is not working at all. The password should be setted first time then return the home page, then when the user open it again the password should be stored but somehow it didn't store it.
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences passfile = getSharedPreferences("ans",0);
String pass = passfile.getString("ans", null);
check.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String answer1 = answer.getText().toString();
//Check that user typed in an answer
if(answer1.length()<8){
Toast.makeText(CheckPwActivity.this, "Answer must be 8 characters long", Toast.LENGTH_SHORT).show();
answer.setText("");
answer.requestFocus();
return;
}
answer.getEditableText().toString();
//check if the answer is valid
if (answer1.equals("ans")) {
Intent intent2 = new Intent(CheckPwActivity.this,MainActivity.class);
startActivity(intent2);
}else{
return;
}
}});
}
public void setPassword(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
Editor preferenceEditor = context.getSharedPreferences("password", 8).edit();
preferenceEditor.putString(key, value);
preferenceEditor.commit();
}
public static String getPassword(String filename) {
return context.getSharedPreferences("password", 2).getString(filename,"");
}

you are using shared preferences wrong, in your set password you get shared preferences but then you get it again but in a different context
this is all you need to use shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
then when you want to set it you use the editor you just got
editor.putString(key,pass).commit;
then to get it from shared preferences you would just do
preferences.getString(key,defaultString);

Related

Integer Shared preference allways returns 0

I am trying to code a simple password check for protecting the settings of my app. The password should be saved in a shared preference. The main calls the setPassword when the sharedPreference returns zero. This is to make sure that there will be a password set, when somebody tries to enter the settings the first time. The setPassword should then set a password and safe it in the sharedPreference. But when checking if there was a password set, the sharedPreference allways returnes 0.
this is my main:
final Intent intentSetPasswords = new Intent(this, SetPasswordActivity.class);
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
passwordToCheck = sharedPreferences.getInt("PASSWORDSETTINGS", 0);
//setting button on click listener
buttonSetings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//check if a password was set muss Überarbeitet werden
passwordToCheck = sharedPreferences.getInt("PASSWORDSETTINGS", 0);
Log.e("password", ""+ passwordToCheck);
if(passwordToCheck==0){
startActivity(intentSetPasswords);
}else{
startActivity(new Intent(MainActivity.this, PasswordCheckActivity.class));
}
}
});
and tis is my setPassword:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_password);
final Intent intentSettings = new Intent(this, SettingsActivity.class);
buttonSetPassword = (Button)findViewById(R.id.buttonSetPassword);
textViewSetPassword = (TextView)findViewById(R.id.textViewSetPasswordText);
editTextPassword = (EditText)findViewById(R.id.passwordNumericSettingsSetPassword);
final Intent intent = new Intent(this, MainActivity.class);
buttonSetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counterButton++;
switch (counterButton){
case 1:
password = editTextPassword.getText().toString();
if (password.length() == 4){
Log.d("First Password", "taken");
buttonSetPassword.setText("Confirm Password!");
editTextPassword.setText("");
}else{
Log.d("First Password", "not taken");
textViewSetPassword.setText("The Password must be\nfour numbers long!");
password = "";
editTextPassword.setText("");
counterButton=0;
}
break;
case 2:
passwordToConfirm = editTextPassword.getText().toString();
if (Integer.parseInt(passwordToConfirm) == Integer.parseInt(password)){
Log.e("password", password);
Log.e("passwordToConfirm", passwordToConfirm);
SharedPreferences sharedPreferences = getSharedPreferences("PASSWORDS", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("PASSWORDSETTINGS", Integer.parseInt(password));
editor.commit();
startActivity(intentSettings);
finish();
}else{
textViewSetPassword.setText("The passwords aren't the same!\nTry again!");
buttonSetPassword.setText("Set Password");
editTextPassword.setText("");
passwordToConfirm = "";
password = "";
counterButton = 0;
startActivity(intent);
}
break;
}
}
});
}
I guess there is a problem with the sharedPreference, but I don't get what.
Easily use the library below to manage data
https://github.com/orhanobut/hawk
Firstly, check counterButton value and ensure case 2 branch is executed.
Secondly the sharedPreferences for setting and the sharedPreferences for getting should be same. you could do like this:
private final static String MyPREFERENCES = "MyPrefs"; //define two class fields
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);//in activity Oncreate() methods.
//and set or get in other place as you want.
First you get sharedpreferences like this
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Later when setting the password you get it as below
SharedPreferences sharedPreferences = getSharedPreferences("PASSWORDS", 0);
They're two different sharedpreferences. Use the first sharedpreferences.
For more info refer to this page https://developer.android.com/training/data-storage/shared-preferences

Display and edit the value stored in the SharedPreferences

Help please, I'm a bit lost, new to all this and trying to learn.
I want to store 3 names and phone numbers in SharedPreferences and display them in individual textviews so a user can edit the name and phone number and also press the number to call the number.
What I have so far is:
public void setWardenName(Context context, String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getString(R.string.), Name);
editor.apply();
}
public void getWardenName(Context context, String prefKey) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name;
}
}
And on the activity screen I have the first texview called:
android:id="#+id/textView2" which was going to be the first name.
So I'm lost, any help is appreciated.
I will set the Warden as your key name and it depends on you if you want to change that. And, I will assume that it is in the same class since you are using 'this' in
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
So here it is..
private void setWarden(String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPref.edit();
editor.putString("Warden", value);
editor.commit();
}
private String getWarden() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPref.getString("Warden", "");
if(!name.equalsIgnoreCase(""))
{
return name;
}
return "";
}
And in your textview you can get it like:
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText(getWarden());

Key-Value Store Data not retrieved

In my app, I am trying to save a key value as zero or one depending on whether a checkbox is checked. I retrieve these values in a different activity. However, when I attempt to retrieve the value, I am getting an empty string:
Saving key values in Activity 1(ScienceCoursesCheck):
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox_APBio:
if (checked) {
setDefaults("APBio", "1");
}
else {
setDefaults("APBio", "0");
break;
}
}}
Retrieving key values in activity 2(MyHome):
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public void myMethod() {
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
String APBio = myPrefs.getString("APBio","");
if (APBio.equals("1")){
Button myButton = new Button(this);
myButton.setText(APBio);
RelativeLayout ll = (RelativeLayout)findViewById(R.id.activity_my_home);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}
Is the second activity accessing the correct SharedPreferences file?
Use the following code for sharedpreference. Call
Util.saveInfo(activityContext,_key,_value)
when you want to save the info. Then call
Util.getInfo(getApplicationContext(),_key)
to get the info.
public class Util{
public static void saveInfo(Context context, String key, String value )
{
try
{
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).apply();
}
catch (Exception ex)
{
Log.e(TAG," saveInfo "+ex+"");
}
}
public static String getInfo(Context context, String key)
{
try {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key,"");
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
The issue is because when you store the items in SharedPreferences you are using
PreferenceManager.getDefaultSharedPreferences
but when you retrieve them you are using
getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
These are two different SharedPreferences files. Try using getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE); for your setting method as well. Or perhaps you meant to use your getDefaults() method in activity 2 instead of myPrefs
That is because you are saving in the DefaultSharedPreferences file
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
and retrieving from another file named "ScienceCoursesCheck"
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
and they are not the same file!
See the difference between getSharedPreferences and getDefaultSharedPreferences in this answer
====
Solution is either to always use DefaultSharedPreferences OR always use the file named "ScienceCoursesCheck" .
The problem is you're saving the values in the DefaultSharedPreference and trying to retrieve the values from the ScienceCoursesCheck preference file.
Try below code for setDefaults method.The getDefaultSharedPreference and getSharedPreference methods are different.
See this link for the difference.
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = getApplicationContext().getDefaultSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
Hope this helps you...

How can i add multiple entries in a shared prefrences file

Can you please tell me how can i use shared prefrences to write multiple entries in a shared prefrences file.Like if i want to add multiple names in the shared pref file
i am using the following code but each time i click on submit button it overrides the previous entry.
public void onClick(View v)
{
SharedPreferences settings = getSharedPreferences("users", 0);
SharedPreferences.Editor editorUser = settings.edit();
editorUser.putString("user", editUser.getText().toString());
editorUser.commit();
}
You have to use different keys, e.g.:
SharedPreferences settings = getSharedPreferences("users", 0);
SharedPreferences.Editor editorUser = settings.edit();
for (int i = 0; i < users.size(); i++)
editorUser.putString("user" + i, users.get(i));
editorUser.commit();
You are facing that overriding issue because you are using the same shared preference key each time to save the value. Assuming that you are using the same EditText for multiple entries, I guess the following snippet will do the trick.
counter=0;
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
settings = getSharedPreferences("users", 0);
SharedPreferences.Editor editorUser = settings.edit();
editorUser.putString("user"+counter, Edittext.getText().toString());
editorUser.commit();
counter++;
Edittext.setText("");
}
});
show.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<counter;i++)
{
Log.i("User "+i, ""+settings.getString("user"+i, ""));
}
}
});
Here, I used the show button OnClickListner just to check for the multiple entries through EditText. But here I would like to suggest you to go for SQLite DB if you really wish to store multiple user info.
This is how you can do this
Go through with these 2 URL this will help you
vogella.
mobile.tutsplus.com
Save
public void saveInformation(String username,String password) {
SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
}
Load
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String password = sharedPreferences.getString("password", "");
}
Edit
private void editDate(){
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("username", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
}
To save multiple users data in will suggest you to create multiple files for each user and then save it in shared pref
Just go through with the diffrence between getDefaultSharedPreferences and getSharedPreferences from here Diffrence Link

Save the user input data for long time

I am writing an app to save password with a log in interface. The user can change the log in password. I use the following code to save the password, so that the password will not reset when the app relaunch.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString("pwd", currentPwd);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
currentPwd = savedInstanceState.getString("pwd");
}
But I found that it can only save the password for a while. When I wait it for a long time, about 1 hours, without reboot the mobile, it will reset my password.
How to save the password so that it will not reset?
you have to save the data using sharedpreferences:
SharedPreferences prefs =
getSharedPreferences("myprefname",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("pwd", "thepassword");
editor.commit();
then you can retreive it:
SharedPreferences prefs =
getSharedPreferences("myprefname",Context.MODE_PRIVATE);
String password=prefs.getString("pwd",null);
You can save that type of information for a long time using sharedPreference.
public class PreferenceData
{
static final String PREF_USER_PASSWORD = "user_password";
public static SharedPreferences getSharedPreferences(Context ctx)
{
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserPassword(Context ctx, String userPassword)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_PASSWORD, userPassword);
editor.commit();
}
public static String getUserPassword(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_PASSWORD, "");
}
}
I have the exact same problem as you or did have. I simply used Shared_Prefs. It saves the login data in an XML file and you read and write to it.
Here's the Android writeup: http://developer.android.com/guide/topics/data/data-storage.html
To write:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key1", username);
editor.putString("key2", password);
editor.commit();
To Read:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String username = settings.getString("key1", null);
String password = settings.getString("key2", null);

Categories

Resources