I have a login activity on app start and I need to check if use has used this app before and then I need to place the username and his password entered recently.
For this I have used shared preferences and used as shown below:
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
username= usernameET.getText().toString();
password= passwordET.getText().toString();
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("username", username).commit();
data.edit().putString("password", password).commit();
}
});
Now I'm getting these values on app restart as shown below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String storedUsername = data.getString("username", "");
String storedPassword = data.getString("password", "");
if (storedUsername != null && storedPassword != null) {
usernameET.setText(storedUsername);
passwordET.setText(storedPassword);
} else {
}
}
Coder, what is your issue? This is not working?
Please, tell us what is happening.
The implementation with SharedPreference would be my suggestion for you, is it not working?
I made a very simple implemention here and it works as usual...
On the onCreate:
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String storedUsername = data.getString("username", "");
String storedPassword = data.getString("password", "");
Toast.makeText(this, "saved Strings, user = " + storedUsername + " pass = " + storedPassword, Toast.LENGTH_LONG).show();
On the click of an ImageButton
#Override
public void onClick(View v) {
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("username", "carlos").commit();
data.edit().putString("password", "password").commit();
}
Sounds like you are not setting the content on the SharedPreferences. Could you please make sure the action is executed?
Didn't really see a question asked but...
data.getString is going to return the default value if it is not set, which you're setting as a blank string(""). Either change your if:
if (!storedUsername.equals("") && !storedPassword.equals(""))
or change your default value to null
String storedUsername = data.getString("username", null);
String storedPassword = data.getString("password", null);
Related
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
I am developing an app,in that i am maintaining Session using Shared Preferences.I that when user login,i am using their email id for further use.But when i tried to use that email in another activity, it is showing null.
Below in my code for mainActivity:
public class main extends AppCompatActivity {
public Button submit;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String email = "emailkey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
submit = (Button) findViewById(R.id.btn_login);
ImageView i1 = (ImageView) findViewById(R.id.imgLogo);
String checkBoxText = "I agree to all the";
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
checkBox.setText(Html.fromHtml(checkBoxText));
checkBox.setMovementMethod(LinkMovementMethod.getInstance());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText e1 = (EditText) findViewById(R.id.input_email);
EditText p1 = (EditText) findViewById(R.id.input_password);
String e = e1.getText().toString();
final String password = p1.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(email, e);
editor.commit();
Here is my code for another activity:
String e,email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internshipsdetails);
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
sharedpreferences.getString(email,e);
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
AQuery mAQuery = new AQuery(InternShipsDetails.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
You can manage session by changing shared preference values after doing logout action and check preference again at the time of login also. You can save current time also in a string at login and logout action. Make sure to use private shared preferences.
You are passing the wrong key to shared Pref because of that you are getting null.
Following is the updated code of yours which will give you the stored email address:
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
e = sharedpreferences.getString(main.email,"");
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
Happy coding !!!
getString (String key, String defValue) method returns a String. So, you need to catch the output in a string variable.
Also, you are passing a nullkey. You need to pass the same key using which you saved the value.
So, in your case it would be
e = sharedpreferences.getString("emailkey","nodata");
I'm newbie into android and today I wanted to implement some SharedPreferences.
Here's my code: (or Image if ou like it more)
#Override
public void onCreate(Bundle savedInstanceState) {
// SOME CODE HERE
// Initialize Shared Preferences
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyData", Context.MODE_PRIVATE);
sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
logMsg(sharedPreferences.toString() + "=>" + s + "=>" + sharedPreferences.getString(s, ""));
}
});
final EditText etId = (EditText) findViewById(R.id.etId);
final EditText etValue = (EditText) findViewById(R.id.etValue);
Button btnSave = (Button) findViewById(R.id.btn_save);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// set Data
logMsg("Id= " + etId.getText().toString() + " Value= " + etValue.getText().toString());
sharedPreferences.edit().putString(etId.getText().toString(), etValue.getText().toString());
if (sharedPreferences.edit().commit()){
logMsg("Success");
}else {
logMsg("Fail");
}
// get Data
logMsg("Id= '" + etId.getText().toString() + "' Value= " + sharedPreferences.getString(etId.getText().toString(), "No Value"));
}
});
//SOME CODE HERE
}
The problem is that after pressing btn_save log says Success on sharedPreferences.edit().commit() but after that I don't retrieve any data with getString() (respectively I retrieve dafault value that is in my case "No Value").
Do you have any idea what's wrong?
Is it necessary to unregister SharedPreferences.OnSharedPreferenceChangeListener?
Thanks.
Each time you call edit(), you get a new instance of SharedPreferences.Editor. You need to do your modifications and commit() (or apply()) on the same editor instance.
Therefore, save the return value of edit() to a variable, and call putString() and commit() on that.
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}
I am using the code for remember my username and password. i have tried a lot of hours for the code for remember my username name and password but i cant success in it.
Here is my code which i have download from internet but it didn't work for me.
I have declared this variable in the extends activity.
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS_PASS = "prefsPassword";
after that I have also declare different variable like below.
public String PREFS_USERS;
public String PREFS_PASS;
String username;
String upass;
and in the click listener i have given the following code.
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
username = etUsername.getText().toString();
upass = etPassword.getText().toString();
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_USERS, username)
.putString(PREFS_PASS, upass)
.commit();
and at the time at retry i have return the following code in the oncreate activity to retry my user name and password.
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USERS, "");
upass = pref.getString(PREFS_PASS, "");
But when I run the application i cant get the username and password.First time when i load the application i checked the remember me check box after log in and log out back from the application and close the application and when come back to it.it was not saved for me.
The problem is in declaring the variables
you have declared
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS_PASS = "prefsPassword";
public String PREFS_USERS;
public String PREFS_PASS; //assigned null here
.putString(PREFS_PASS, upass) //here value of PREFS_PASS is null
Use the following code
better do like the folowing
public String PREFS_USERNAME= "prefsUsername";
public String PREFS_PASSWORD="prefsPassword";
Store the data as using following code
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
passwordInString = password.getText().toString();
userNameInString = username.getText().toString();
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_USERNAME, userNameInString)
.putString(PREFS_PASSWORD, passwordInString)
.commit();
retrieve the data like the following
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String usernameName = pref.getString(PREFS_USERNAME, "");
String upassWord = pref.getString(PREFS_PASSWORD, "");
Thanks
Deepak
It should look something like this (obviously you can use global vars so you dont have to specify them in several places):
String PREFS = "MyPrefs";
SharedPreferences mPrefs;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPrefs = getSharedPreferences(PREFS, 0);
//check if the remember option has been check before
boolean rememberMe = mPrefs.getBoolean("rememberMe", false);
if(rememberMe == true){
//get previously stored login details
String login = mPrefs.getString("login", null);
String upass = mPrefs.getString("password", null);
if(login != null && pass != null){
//fill input boxes with stored login and pass
EditText loginEbx = (EditText)findViewById(R.id.login_box);
EditText passEbx = (EditText)findViewById(R.id.pass_box);
loginEbx.setText(login);
passEbx.setText(upass);
//set the check box to 'checked'
CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.remeber_cbx);
rememberMeCbx.setChecked(true);
}
}
}
private void saveLoginDetails(){
//fill input boxes with stored login and pass
EditText loginEbx = (EditText)findViewById(R.id.login_box);
EditText passEbx = (EditText)findViewById(R.id.pass_box);
String login = loginEbx.getText().toString();
String upass = passEbx.getText().toString();
Editor e = mPrefs.edit();
e.putBoolean("rememberMe", true);
e.putString("login", login);
e.putString("password", upass);
e.commit();
}
private void removeLoginDetails(){
Editor e = mPrefs.edit();
e.putBoolean("rememberMe", false);
e.remove("login");
e.remove("password");
e.commit();
}
You would probably call the saveLoginDetails() & removeLoginDetails() methods in the OnClick listener:
CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.remeber_cbx);
boolean isChecked = rememberMeCbx.isChecked();
if(isChecked){
saveLoginDetails();
}else{
removeLoginDetails();
}
I hope you can find it useful
U can do this.. create a boolean variable with default value "false" and set a boolean value to true when user choses for rememberMe and put an if condition before validating user password and other stuff.. and use the boolean value in this condition..
SharedPreferences myPrefs;
onCreate()
{
myPrefs=this.getSharedPreferences("PREF_NAME",Context.MODE_PRIVATE);
if(myPrefs.getBoolean("firstTime", false))
{
startActivity(new Intent(this,SeeRecordsActivity.class));
finish();
}
}
on signIn button:
boolean c=chkbox.isChecked();
if(c==true)
{
SharedPreferences.Editor editor=myPrefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}