Use sharedPreference to save account and password - android

public class LoginActivity extends BaseActivity{
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
accountEdit =(EditText)findViewById(R.id.account);
passwordEdit = (EditText)findViewById(R.id.password);
rememberPass=(CheckBox)findViewById(R.id.remember_pass);
login = (Button)findViewById(R.id.login);
editor.putBoolean("remember_password",false);
boolean isRemember = pref.getBoolean("remember_password",false);
if(isRemember){
String account = pref.getString("account", "");
String password =pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String account =accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (account.equals("admin")&& password.equals("123456"))
{ editor = pref.edit();
if(rememberPass.isChecked())
{
editor.putBoolean("remember_password",true);
editor.putString("account",account);
editor.putString("password",password);
}
else
{
editor.clear();
}
editor.commit();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(LoginActivity.this,"account for password is invalid",
Toast.LENGTH_LONG).show();
}
}
});
}
}
I use Eclipse to code android.I got an error in LogCat,which is NullPointerException cause by "boolean isRemember = pref.getBoolean("remember_password",false);"
I don't know why.How to use getBoolean correctly?
Thanks in advance.

Because pref=null at
boolean isRemember = pref.getBoolean("remember_password",false);
initialized it before used
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

You have to create the object of the Shared preference than you can use it in yours code
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
than use
boolean isRemember = pref.getBoolean("remember_password",false);

Use this simple way to use prefrences
private SharedPreferences getPrefs;
//in OnCreate
getPrefs = PreferenceManager.getDefaultSharedPreferences(Activity_Name.this);
//At insertion value
getPrefs.edit().putBoolean("Key_Name", false).commit();
//At fetching Values
boolean a = getPrefs.getBoolean("Key_Name", false);

Related

Storing values in SharedPreferences on button click

How can I store already existing string value in SharedPreferences on button click? I have a TextView and a button: the TextView contains certain string and I want to store that in SharedPreferences on button click.
To write it:
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Yourkey", textView.getText()+"");
editor.commit();
}
});
And to read it:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String string = sharedPref.getString("Yourkey","default");
Here are methods which I use everytime to store data in shared-preferences:
private SharedPreferences app_prefs;
private final String DEVICE_TOKEN = "device_token";
public PreferenceHelper(Context context) {
app_prefs = context.getSharedPreferences(AndyConstants.PREF_NAME,
Context.MODE_PRIVATE);
this.context = context;
}
public void putDeviceToken(String deviceToken) {
Editor edit = app_prefs.edit();
edit.putString(DEVICE_TOKEN, deviceToken);
edit.commit();
}
public String getDeviceToken() {
return app_prefs.getString(DEVICE_TOKEN, null);
}
In the first method I create the shared-preferances object, in the second method I use it to put data and in third method to get data any where you need.

clear the value of sharedpreferences

i am kind of new to android programming , i am designing a program that has login page and main page.When i sign in for the first time with a username and password, i created a sharedpreferences to remember that username and whenever i enter program , it skips login page and redirects me to main page.What i want to do is, when i press logout button in login page ,i want sharedpreferences forget the value of username in my database(it wont delete it from database) and force me to login me again with the same or different username and password , and i dont want to be redirected to main page when i enter application.I found something like SharedPreferences.Editor.remove() , SharedPreferences.Editor.clear(),commit() ,etc.. But code didnt work.Can you help?
public static class SaveSharedPreference {
static final String PREF_USER_NAME = "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx) {
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Button btnSignIn, btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uye_kayit_giris);
if (SaveSharedPreference.getUserName(UyeKayitGirisActivity.this).length() == 0) {
Intent i = new Intent(UyeKayitGirisActivity.this, MainActivity.class);
startActivity(i);
// finish();
}
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Refference Of Buttons
btnSignIn = (Button) findViewById(R.id.buttonSignIN);
btnSignUp = (Button) findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP = new Intent(getApplicationContext(), SignUPActivity.class);
startActivity(intentSignUP);
}
});
Button btn_exit;
// super.onCreate(savedInstanceState);
// setContentView(R.layout.main1);
btn_exit = (Button) findViewById(R.id.buttonLogOUT);
btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WHAT SHOULD I WRITE IN HERE?????????????
Toast.makeText(UyeKayitGirisActivity.this, "ÜYE GİRİŞİ TEKRAR ZORUNLU HALE GETİRİLDİ!!!", Toast.LENGTH_LONG).show();
}
});
}
Try like this
SharedPreferences pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
Here is the Method
private void removePreference(Context context, String prefsName, String key) {
SharedPreferences preferences = context.getSharedPreferences(prefsName, Activity.MODE_PRIVATE);
android.content.SharedPreferences.Editor editor = preferences.edit();
editor.remove(key);
editor.apply();
}
You can call it like:
public void removeUser() {
removePreference(context, FILENAME, KEY_USER);
}
Since you have mentioned that you do NOT want to delete the value of login from shared preference but only ask for login page each time, I believe you are looking for something where you want to clear application cache programatically.
Please check, Clear Cache in Android Application programmatically and Clear Application's Data Programmatically
It is also worth reading this wonderful answer - Don't delete database or shared Preference on clear app
To remove them all SharedPreferences.Editor.clear() followed by a commit()

Shared preferences not working correctly

I'm trying to store some strings in a shared preference file and then retrieve them in another activity, except it doesn't seem to be working. Any guidance as to where im going wrong would be much appreciated. Many thanks.
public void save(View view) {
SavePreferences("name", nameS);
SavePreferences("current", currentS);
SavePreferences("goal", goalS);
SavePreferences("CurrentBmi", cBmiS);
SavePreferences("goalBmi", gBmiS);
Toast.makeText(this, "profile Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public class Progress extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String test = sharedPreferences.getString("name", "");
String test2 = sharedPreferences.getString("current", "");
TextView testy = (TextView) findViewById(R.id.textView1);
testy.setText(test);
TextView testz = (TextView) findViewById(R.id.test2);
testz.setText(test2);
}
With the code you have you are limiting the access of sharedpreferences to activity(context) level.
Values saved in activity Activity MainActivity will not be available in activity Progress since you are using getPreferences(MODE_PRIVATE);
Change this to
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
or
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
getPreferences:
public SharedPreferences getPreferences (int mode)
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

how to save some value in sharedpreferences and get that in next activity

I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)

Android:problem in remember me functionality of login Activity

i have create login page with 2 EditText and checkbox and login button.
if i set checkbox to Enabled i want to save data so next time user doesn't need to fill that fields..
i have uses this code but no luck..
public class LoginPage extends Activity {
EditText d_ID;
EditText password;
CheckBox cb;
ImageButton ib;
public static final String PREFS_NAME = "MyPrefsFile";
public String PREFS_USER;
public String PREFS__PASS;
String username;
String upass;
SharedPreferences pref
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.loginpage);
d_ID = (EditText) findViewById(R.id.dulzuID);
password = (EditText) findViewById(R.id.dulzuPASS);
cb = (CheckBox) findViewById(R.id.remember);
ib = (ImageButton) findViewById(R.id.login);
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, null);
upass = pref.getString(PREFS__PASS, null);
d_ID.setText(username);
password.setText(upass);
ib.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(LoginPage.this, Features.class));
}
});
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
PREFS_USER = d_ID.getText().toString();//get user name from EditText
PREFS__PASS = password.getText().toString();//get user Password from EditText
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().putString(PREFS_USER, username).putString(PREFS__PASS, upass).commit();
}
});
}
}
Any help??
Thanks...
I think you are confusing the variables for retrieving the value of the users password and the variables that identify the username/password values in the preferences. I think that you intend these:
public String PREFS_USER;
public String PREFS__PASS;
to be the identifiers for your stored username and password, however you then set them to be the values that you have pulled from the corresponding EditTexts. I have rewritten some of the code for you:
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS__PASS = "prefsPassword";
...
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, "");
upass = pref.getString(PREFS__PASS, "");
...
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
username = d_ID.getText().toString();//get user name from EditText
upass = password.getText().toString();//get user Password from EditText
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().putString(PREFS_USER, username).putString(PREFS__PASS, upass).commit();
}
Personally, I wouldn't do it like that though. I would check the value of the checkbox when the user submits the form, and only save the username & password at that point. What if the user unchecks and then rechecks the tick box before they have entered their password? You will save empty values and annoy your users.
You are doing small mistake in this part:
if (cb.isChecked()) {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, null);
upass = pref.getString(PREFS__PASS, null);
d_ID.setText(username);
password.setText(upass);
}
As your view is rendered each time when new activity starts.cb.isEnabled() will always give false because it is not enabled that time.
You can do stuff for your sol like this.
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
if(!pref.getstring(PREFS_USER,null).equals(null)||!pref.getstring(PREFS_USER,null).equals(""))
{username = pref.getString(PREFS_USER, null);
d_ID.setText(username);}
and same for password field
One thing that I would like to tell you: do not store the values when user clicks on check box save it when user presses login button.
If user clicked that check box when he has not entered details the you will save null values.
And why don't you serialize both the objects and save it to memory and again deserialize it when you need to read it?
public void serializeCredentials(String Username,String Password) {
try {
FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oStream = new ObjectOutputStream(fStream);
oStream.writeObject(Username) ;
FileOutputStream fos = openFileOutput(passwordfile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(Password) ;
oStream.flush() ;
oStream.close() ;
oos.flush() ;
oos.close() ;
Log.v("Serialization success", "Success");
} catch (Exception e) {
Log.v("IO Exception", e.getMessage());
}
}
Don't forget to deserialize when reading data; you can deserialize it similarly.
I think you need to write/initialize this line inside onCreate() method.
SharedPreferences pref;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.loginpage);
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
...
}
try doing the editing line by line.. at least in my case, it did the trick..
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
PREFS_USER = d_ID.getText().toString();//get user name from EditText
PREFS__PASS = password.getText().toString();//get user Password from EditText
SharedPreferences.Editor prefEditor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
prefEditor.putString(PREFS_USER, username);
prefEditor.putString(PREFS__PASS, upass);
prefEditor.commit();
}
});
And it would be much better if you follow N-JOY's suggestion to trigger saving data to SharedPreferences during login button click..

Categories

Resources