android - sharedpreferences return null value - android

I'm trying to use sharedpreferences to check whether the user logged in before they start using the app. I save the username in shredpreferences when user log in.
Login.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btnLogin = (Button) findViewById(R.id.buttonlogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View adapt) {
EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
userName = usernameEditText.getText().toString();
EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
userPassword = passwordEditText.getText().toString();
if (userName.matches("") && userPassword.matches("")) {
toast("Please enter Username and Password");
return;
} else if (userName.matches("") || userName.equals("")) {
toast("Please enter Username");
return;
} else if (userPassword.matches("") || userPassword.equals("")) {
toast("Please enter Password");
return;
} else {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", userName);
editor.commit();
new DownloadFilesTask().execute();
}
}
});
}
private void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
}
protected void onPostExecute(Void result) {
toast("user logged in");
startActivity(new Intent(Login.this, MainActivity.class));
finish();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
}
}
and I tried to check the username value before I start my mainactivity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username =sharedPreferences.getString("MEM1", "");
if(username.equalsIgnoreCase("")||username.length()==0)
{
toast("username is null");
startActivity(new Intent(MainActivity.this, Login.class));
finish();
}
but the username is always null. Please help. Thanks

Calling getPreferences means that you have to be in the same activity. Using getSharedPreferences allows you to share the preferences between activities. You just have to define a name for the preferences when calling getSharedPreferences("Pref name here", MODE_PRIVATE);

Write below Code instead of your code to save username into sharedpreferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("MEM1", userName);
editor.commit();
And Use below code For Get Preferences Value.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("MEM1","");

private final String TAXI_SPREF = "TAXI_SHARED_PREFERENCES";
//set-save data to shared preferences
SharedPreferences.Editor sPEditor = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).edit();
sPEditor.putInt("USERID", etUserID.getText().toString());
sPEditor.putString("EMAIL", etEmail.getText().toString());
sPEditor.apply();
//get data from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE);
int userID = sharedPreferences.getInt("USERID", 0);
string email = sharedPreferences.getString("EMAIL", 0);
//////// or /////
String email = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).getString("EMAIL","EMPTY");
if (!email.equals("EMPTY")){
etEmail.setText(email);
}

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

Null pointer exception on invoking Shared preference object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
When compiling my code I'm get this error
java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()'
and I still can't figure why. For these error My App got crash. Please help on this I'm not able to find the what exact mistake i did.
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
at com.chatbook.loki.chatbook.SessionManger.<init>(SessionManger.java:16)
at com.chatbook.loki.chatbook.Login.onCreate(Login.java:44)
at android.app.Activity.performCreate(Activity.java:6001)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) 
Here is my code
SessionManager.java
public class SessionManger {
SharedPreferences pref;
SharedPreferences.Editor editor = pref.edit();
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "exmaple";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
public SessionManger(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void createLoginSession(String email, String password){
editor.putBoolean(IS_LOGIN,true);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_PASSWORD, password);
editor.commit();
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN,true);
}
public void checkLogin(){
if(!this.isLoggedIn()){
Intent in = new Intent(_context,Login.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(in);
}
}
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String, String>();
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
return user;
}
public void logout(){
editor.clear();
editor.commit();
Intent in = new Intent(_context,Login.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(in);
}
}
and my Login activity file
public class Login extends AppCompatActivity {
Button b1,b2,b3;
EditText e1,e2;
FirebaseAuth auth;
ProgressBar pgbar;
SessionManger session;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
b1 = (Button) findViewById(R.id.logBsign);
b2 = (Button) findViewById(R.id.logBlog);
b3 = (Button) findViewById(R.id.logBreset);
e1 = (EditText) findViewById(R.id.logeditemail);
e2 = (EditText) findViewById(R.id.logeditpass);
pgbar = (ProgressBar) findViewById(R.id.progressBar);
session = new SessionManger(context.getApplicationContext());
}
public void signup(View v) {
Intent in = new Intent(Login.this, SignUp.class);
startActivity(in);
}
public void login(View v){
/*Intent in = new Intent(Login.this, MainActivity.class);
startActivity(in);*/
final String email = e1.getText().toString().trim();
final String password = e2.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(getApplicationContext(),"Enter email address", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(getApplicationContext(), "Enter password", Toast.LENGTH_SHORT).show();
return;
}
pgbar.setVisibility(View.VISIBLE);
auth.signInWithEmailAndPassword(email,password).addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
pgbar.setVisibility(View.GONE);
if(!task.isSuccessful()){
if(password.length() < 6){
e1.setError(getString(R.string.minimum_password));
}else{
Toast.makeText(Login.this, getString(R.string.auth_failed),Toast.LENGTH_SHORT).show();
}
}else{
session.createLoginSession(email, password);
Intent in = new Intent(Login.this, MainActivity.class);
startActivity(in);
//finish();
}
}
});
}
public void reset(View v){
Intent in = new Intent(Login.this, ResetPassword.class);
startActivity(in);
}
//To exit from App
public boolean exit = false;
#Override
public void onBackPressed() {
if(exit){
finish();;
}
else{
Toast.makeText(this,"Press again to exit",Toast.LENGTH_SHORT).show();
exit = true;
}
}
}
Do not
session = new SessionManger(context.getApplicationContext());
Do
session = new SessionManger(Login.this);
And
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
Then
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
Shared preferences can be edited like below ,pass correct name
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, name);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString(key, "default value");
fix the global variable cause null
SharedPreferences.Editor editor = pref.edit(); <-- wrong pref cause null
SharedPreferences.Editor editor; <-- just this
Optional
#SuppressLint("CommitPrefEdits")
public SessionManger(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor = pref.edit();
//editor.apply(); //no need for apply
}
It's because your pref is null...
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences pref;
SharedPreferences.Editor editor = pref.edit();
pref is null;

Issues with implementing the login using shared preference

I have mentioned my complete code for the login and logout process to my application. Sometimes this code works but sometimes it just allows me to go to menu activity even without login. FYI: this code really worked earlier once i wanted to implement the remember me option, then only all these issues came up. can anyone check this and find me my issue or suggest me if u got any proper code for this process. when i logout and and open the application sometimes i can see the menu.
I have used shared preference and not using sessions for login and logout. is it correct. Im bit confused i would really appreciate any help. thanx in advance.
login code
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
EditText emailET;
EditText pwdET;
String email;
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Login process started...",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),
"Login error, invalid email",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(
getApplicationContext(),
"Login error, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
final TextView textView = (TextView) findViewById(R.id.link_to_landing);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
}
}
logout code
final RelativeLayout relativeLayout3 = (RelativeLayout) rootView
.findViewById(R.id.logoutlistview);
relativeLayout3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null ) {
Editor editor = pref.edit();
editor.clear();
editor.commit();
email = "";
password = "";
firstname = "";
lastname = "";
// show login form
Intent intent = new Intent(getActivity(),
LActivity.class);
startActivity(intent);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
}
}
});
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
Please check the below link which might help you.
http://androidapplicationdeveloper.weebly.com/login-and-logout-useing-sharedprefrences.html
In your code you have didn't set values of sharedpreference to blank while logout.
Hope it will help you.

Sharing the SharedPreferences

I have 2 activities namely MainActivity and OKActivity. The MainActivity statically checks for a password and lets you go to the OKActivity. I have used SharedPrefrences in the OKActivity for changing the password to a new one.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText password = (EditText) findViewById(R.id.editText_Password);
Button enter = (Button) findViewById(R.id.button);
enter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String user_pass;
user_pass = password.getText().toString();
if (user_pass.isEmpty()) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Password Field Cannot Be Empty");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
else
if (user_pass.equals("123")) {
Toast.makeText(MainActivity.this, "Welcome!", Toast.LENGTH_SHORT).show();
Intent I = new Intent("com.mavenmaverick.password.OKActivity");
startActivity(I);
}
else
if(user_pass != ("123")){
Toast.makeText(MainActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Incorrect Password");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
}
});
}
public class OKActivity extends Activity {
EditText newPassword;
String newUserPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok);
newPassword = (EditText) findViewById(R.id.new_password);
newUserPassword = newPassword.getText().toString();
getpasswordSharedPreferences();
Button changePassword = (Button) findViewById(R.id.button_change);
changePassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
newUserPassword = newPassword.getText().toString();
getpasswordSharedPreferences();
setSharedPreferences();
}
});
}
private String getpasswordSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
String password = userPassword.getString("THE_PASSWORD", "123");
return password;
}
private void setSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
SharedPreferences.Editor password_edior = userPassword.edit();
password_edior.putString("THE_PASSWORD", newUserPassword);
password_edior.commit();
Toast.makeText(OKActivity.this, "Password Change Succesful", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OKActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Done!");
dialogBuilder.setMessage("New Password : "+newUserPassword);
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
How can I access the SharedPrefrences in OKActivity for the password and use it in my MainActivity to allow access thereby making things dynamic over user-interaction cycles.
Just access the SharedPreferences in your OKActivity and in your MainActivity. The trick is to use the same TAG name - in your case it's 'USER_PASSWORD'.
Have a look at this --> SharedPreferences
Create a SharedPrefrences.java //then we can use when ever we need
public class SharedPrefrences {
public static void saveData(String name, String value, Context context) {
try {
SharedPreferences settings = context
.getSharedPreferences(Configuration.getPrefsName(), 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(name, value);
editor.commit();
} catch (NullPointerException ignored) {
}
}
public static String getData(String name, Context context) {
try {
SharedPreferences settings = context
.getSharedPreferences(Configuration.getPrefsName(), 0);
return settings.getString(name, "");
} catch (NullPointerException ignored) {
return "";
}
}
}
//In MainActivity
SharedPrefrences.saveData("Password","123456", getApplicationContext());
//In OKActivity
String passwordfromMainActivty = PreferencesUtils.getData("Password", getApplicationContext());
//To Add Newpassword
SharedPrefrences.saveData("NewPassword","abcd", getApplicationContext());
You get the same way in both activity's. Do get of your SharedPreferences with the same TAG.
private String getpasswordSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
String password = userPassword.getString("THE_PASSWORD", "123");
return password;
}
Maybe you can put this method's in other class, and call when you want from all activities:
You can put your set method here too
For example:
public class SharedPrefs {
private static final String SHARED_PREF = "USER_PASSWORD";
private static final String KEY_PASSWORD = "THE_PASSWORD";
public static void getStoredSharedPref(Context context, String key, String value) {
SharedPreferences sharedPref = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(propertyKey, value);
editor.commit();
}
}
and then call in your activities
SharedPrefs.getStoredSharedPref(context, SharedPrefsUtils.KEY_PASSWORD,"1234");

Android SharedPreferences not loading and saving properly

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);
}
}

Categories

Resources