Hi I'm using user login screen. In that I'm using shared preferences to store the user details and store whether the user is logged in or not. I'm using splash screen and in that splash activity I checked a value from sharedpreference to know whether the user is already logged in or not.If the user logged in,then after splash it will go to dashboard otherwise it goes to login screen.But i am getting null pointer error.please help me.
My shared prefrence class is:
public class Userloginsession {
public static final String IS_User_login = "isuserloggedin";
// {"did":"1","drivername":"arul ji","dusername":"PIKDRIVER01","logid":"79"}
//Driver Login details
//From DRIVER
public static final String IS_SNO = "sno";
public static final String IS_USERNAME = "userloginname";
public static final String IS_USERPASSWORD = "userloginpassword";
//
public static final String IS_EMP_ID = "emp_id";
//
//From Json Driver
public static final String IS_FIRST_NAME = "first_name";
public static final String IS_LAST_NAME = "last_name";
public static final String IS_IMAGE = "image";
static SharedPreferences user_details;
// Editor Reference for sharedpref
SharedPreferences.Editor user_details_editor;
public Userloginsession(final Context applicationContext) {
// create sharedpreff file "driverSession" for DRIVERLOGINACTIVITY
user_details = applicationContext.getSharedPreferences("usersession",0);
//Edit pfeff file
user_details_editor = user_details.edit();
user_details_editor.apply();
}
public static boolean isuserLoggedIn() {
return user_details.getBoolean(IS_User_login, false);
}
public void createuserLogin(String passwordp, String username, String SNO, final String EMP_ID, final String FIRST_NAME, final String LAST_NAME, final String Image) {
user_details_editor.putBoolean(IS_User_login, true);
user_details_editor.putString(IS_USERNAME, username);
user_details_editor.putString(IS_USERPASSWORD, passwordp);
user_details_editor.putString(IS_SNO, SNO);
user_details_editor.putString(IS_EMP_ID, EMP_ID);
user_details_editor.putString(IS_FIRST_NAME, FIRST_NAME);
user_details_editor.putString(IS_LAST_NAME, LAST_NAME);
user_details_editor.putString(IS_IMAGE, Image);
user_details_editor.commit();
}
public HashMap<String, String> isGetuserDetails() {
// Use hashmap to store user credentials
final HashMap<String, String> userdetailsmap = new HashMap<>();
// Driv pass
userdetailsmap.put(IS_USERNAME, user_details.getString(IS_USERNAME, null)); // Driv Pass
// Driver user name
userdetailsmap.put(IS_USERPASSWORD, user_details.getString(IS_USERPASSWORD, null));
// Driver ID
userdetailsmap.put(IS_SNO, user_details.getString(IS_SNO, null));
//Driver Name
userdetailsmap.put(IS_EMP_ID, user_details.getString(IS_EMP_ID, null));
userdetailsmap.put(IS_FIRST_NAME, user_details.getString(IS_FIRST_NAME, null));
userdetailsmap.put(IS_LAST_NAME, user_details.getString(IS_LAST_NAME, null));
userdetailsmap.put(IS_IMAGE, user_details.getString(IS_IMAGE, null));
return userdetailsmap;
}
public void clearAllvalues() {
user_details_editor = user_details.edit();
user_details_editor.clear();
user_details_editor.apply();
}
}
My splashscreen acticty is :
public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen2);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (Userloginsession.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();
} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}
My error is:
Process: com.example.notebook.dptextiles, PID: 214 java.lang.NullPointerException:
Attempt to invoke interface method 'boolean android.content.SharedPreferences.getBoolean(java.lang.String, boolean)' on a null object reference
at com.example.notebook.dptextiles.fragments.Userloginsession.isuserLoggedIn(Userloginsession.java:45
at com.example.notebook.dptextiles.Splashscreen$1.run(Splashscreen at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
You are using Userloginsession.isuserLoggedIn() directly
use it like this
Userloginsession login=new Userloginsession(getApplicationContext());
if (login.isuserLoggedIn())
The problem is your are not initializing the sharedpreference. Ie. Userloginsession not get initialized. For that you need to give activity context.
the overall class should be
public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen2);
Userloginsession login=new Userloginsession(getApplicationContext());
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (login.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();
} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}
Make sure your shared preferences is initialised before query. Put a breakpoint and debug.
you user_details shared preference is null..
in your Splash Activity:
initialize it like:
Userloginsession session = new Userloginsession(Splashscreen.this);
if (session.isuserLoggedIn()) {
First create a seperate Preference class
PrefManager.java
package name;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
/**
* Created by Ravi on 08/07/15.
*/
public class PrefManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "MegaInfomatix";
// All Shared Preferences Keys
private static final String KEY_IS_WAITING_FOR_SMS = "IsWaitingForSms";
private static final String KEY_MOBILE_NUMBER = "mobile_number";
private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_MOBILE = "mobile";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setIsWaitingForSms(boolean isWaiting) {
editor.putBoolean(KEY_IS_WAITING_FOR_SMS, isWaiting);
editor.commit();
}
public boolean isWaitingForSms() {
return pref.getBoolean(KEY_IS_WAITING_FOR_SMS, false);
}
public void setMobileNumber(String mobileNumber) {
editor.putString(KEY_MOBILE_NUMBER, mobileNumber);
editor.commit();
}
public String getMobileNumber() {
return pref.getString(KEY_MOBILE_NUMBER, null);
}
public void createLogin(String name, String email, String mobile) {
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_MOBILE, mobile);
editor.putBoolean(KEY_IS_LOGGED_IN, true);
editor.commit();
}
public boolean isLoggedIn() {
return pref.getBoolean(KEY_IS_LOGGED_IN, false);
}
public void clearSession() {
editor.clear();
editor.commit();
}
public HashMap<String, String> getUserDetails() {
HashMap<String, String> profile = new HashMap<>();
profile.put("name", pref.getString(KEY_NAME, null));
profile.put("email", pref.getString(KEY_EMAIL, null));
profile.put("mobile", pref.getString(KEY_MOBILE, null));
return profile;
}
}
do this in LoginActivity class and in onCreate method
before onCreate method create preference class object
Preference pref;
pref = new PrefManager(this);
if (pref.isLoggedIn()) {
Intent intent = new Intent(SmsActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
Related
I am very new in android.In my app I make a login page.I use Shared Preferences for session.it works fine but a problem when i close my app and again open then login page comes.I want when user press logout button only that time login page will come.
this is my SharedPreferences class
public class SharedPrefManager {
//the constants
private static final String SHARED_PREF_NAME = "dreamzsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_PHONE = "keyphone";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getUserid());
editor.putString(KEY_PHONE, user.getUserphno());
editor.putString(KEY_USERNAME, user.getUsername());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_PHONE, null),
sharedPreferences.getInt(KEY_ID, -1)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
this is my login method in login class
private void userLogin() {
//first getting the values
final String username = UsernameEt.getText().toString();
final String password = PasswordEt.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
UsernameEt.setError("Please enter your username");
UsernameEt.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
PasswordEt.setError("Please enter your password");
PasswordEt.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("vuserphno", username);
params.put("votp", password);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);//this URLs is a class where URL_LOGIN is login url
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
JSONObject obj = new JSONObject(s);
JSONArray array = obj.getJSONArray("user");
for (int i = 0; i < array.length(); i++) {
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
//creating a new user object
User user = new User(
userJson.getString("username"),
userJson.getString("userphno"),
userJson.getInt("userid")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
}
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
please tell me where is the problem and how I can solve this problem.
Thanks.
In your LoginActivity, check for login state and change activity, finish itself so it's clear from the back stack.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance().isLoggedIn(this)) {
startActivity(this, MainActivity.class);
finish();
return;
}
// ...
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity
public class LoginNewActivity extends Activity {
public SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView toRegister = (TextView) findViewById(R.id.link_to_register);
toRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
Button bLogin = (Button) findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsnm.getText().toString();
String password = etPswd.getText().toString();
new UserLoginTask().execute(username, password);
}
});
}
public class UserLoginTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_MESSAGE = "message";
private static final String TAG_NAMA = "nama_user";
private static final String TAG_USERNAME = "username";
private static final String TAG_HAKAKSES = "role";
private static final String TAG_ERROR = "error";
private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String nama = "";
int iduser = 0;
String email = "";
String hakakses = "";
int error_message = 0;
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
nama = json.getString(TAG_NAMA);
email = json.getString(TAG_USERNAME);
hakakses = json.getString(TAG_HAKAKSES);
error_message = json.getInt(TAG_ERROR);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(error_message == 1) {
pdLoading.dismiss();
session.setLogin(true);
session.setStatus(hakakses);
session.setNama(nama);
session.setUsername(email);
session.setId(iduser);
Toast.makeText(LoginNewActivity.this, hakakses,
Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
//intent.putExtra("nama", nama);
//intent.putExtra("email", email);
//intent.putExtra("hakakses", hakakses);
//startActivity(intent);
//LoginNewActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
}
}
}}
and this is my sharedPreferences
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Hlls";
private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
private static final String KEY_IS_USER = "isStatus";
private static final String KEY_IS_NAMA = "isNama";
private static final String KEY_IS_USERNAME = "isUsername";
private static final String KEY_IS_IDUSER = "isIdUser";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn){
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified");
}
public void setId(int isIdUser){
editor.putInt(KEY_IS_IDUSER, isIdUser);
editor.commit();
Log.d(TAG, "ID User akses session modified");
}
public void setStatus(String isStatus){
editor.putString(KEY_IS_USER, isStatus);
editor.commit();
Log.d(TAG, "User akses session modified");
}
public void setNama(String isNama){
editor.putString(KEY_IS_NAMA, isNama);
editor.commit();
Log.d(TAG, "Username session modified");
}
public void setUsername(String isUsername){
editor.putString(KEY_IS_USERNAME, isUsername);
editor.commit();
Log.d(TAG, "Username session modified");
}
public String isNama(){
return pref.getString(KEY_IS_NAMA, "");
}
public int isId(){
return pref.getInt(KEY_IS_IDUSER, 0);
}
public String isUsername(){
return pref.getString(KEY_IS_USERNAME, "");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String isStatus(){
return pref.getString(KEY_IS_USER, "");
}
}
help me for this error, sorry for bad english
NullPointerException is thrown when an application attempts to use an
object reference that has the null value .
You should call this in your ONCREATE section .
session=new SessionManager(LoginNewActivity.this);
Finally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
session=new SessionManager(LoginNewActivity.this);
Use mode private instead of private mode
pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It is flag provided by android itself you need not assign any other flag to it.
and you have not initialized session manager context is null.
I guess you are not initializing your Shared Preference class.
SessionManager session = new SessionManager(this);
In case its true
Please try and make it a singleton class as a general practise
Something like this
public final class PreferenceManager {
private static SharedPreferences preferences;
/**
* Private constructor to restrict the instantiation of class.
*/
private PreferenceManager() {
throw new AssertionError();
}
public static SharedPreferences getInstance(Context context) {
if (preferences == null && context != null) {
preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
return preferences;
}
}
You need to do the following in your Activity:
session = new SessionManager(LoginNewActivity.this);
You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.
I'm storing data on sharedpreferences when user is logged in and setting it in a textview. I want to remove one specific data when user logged out. The problem is data is being stored but not removing. I have tried below code.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "NaafcoPref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_ID = "id";
public static final String KEY_RESULT = "result";
public static final String SCAN_RESULT = "s_result";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String id) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_ID, id);
editor.commit();
}
public void getResult(String result) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_RESULT, result);
editor.commit();
}
public void getScanResult(String scanResult) {
editor.putString(SCAN_RESULT, scanResult);
editor.commit();
}
public void checkLogin() {
if (!this.isLoggedIn()) {
Intent i = new Intent(_context, PointActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_ID, pref.getString(KEY_ID, null));
user.put(KEY_RESULT, pref.getString(KEY_RESULT, null));
user.put(SCAN_RESULT, pref.getString(SCAN_RESULT, null));
return user;
}
public void logoutUser() {
editor.remove(SCAN_RESULT).clear().commit();
//editor.clear();
//editor.commit();
Intent i = new Intent(_context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
To remove specific values: SharedPreferences.Editor.remove() followed by a commit()
To remove them all SharedPreferences.Editor.clear() followed by a commit()
If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.
Try this,
public void logoutUser() {
SharedPreferences sp = Preferences.getInstance().pref;
SharedPreferences.Editor editor = sp.edit();
editor.remove(SCAN_RESULT);
editor.commit();
Intent i = new Intent(_context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
You need to reinitialize sharepreference editer to clear data
public void logoutUser() {
editor = pref.edit();
editor.clear().commit();
Intent i = new Intent(_context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
Try implementing this for logout:
/**
* Clear All user preferences
* Use this when user logs out
*/
public void clearPreferences() {
isLoggedIn(); // this will set the login as false
pref.edit().clear().apply();
//also clear from default preferences
SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(context);
defaultPref.edit().clear().apply();
}
First you need to create singleton class like PreferenceManager
private PreferenceManager(Context ctx) {
prefs = ctx.getApplicationContext().getSharedPreferences(ctx.getPackageName(), Context.MODE_PRIVATE);
editor = prefs.edit();
}
public static PreferenceManager getInstance(Context ctx) {
if (sInstance == null) {
sInstance = new PreferenceManager(ctx);
}
return sInstance;
}
You can use below snippet
public void clearPreference() {
editor.remove("your preference key that you want to clear");
.
.add all preference key that you want to clear
.
editor.commit();
}
SharedPreferences pref = context.getSharedPreferences("s_result", Context.MODE_PRIVATE);
pref.edit().clear().commit();
I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you
I'm trying to display a "rate us" dialog box the 5th time the user logs in to the app. On registering, the sharedpreference LOG_COUNT is set to 0 and the value of another shared prefernce LOG_BOOLEAN is set to true.
When the user logs in the first time, I check if the value of LOG_BOOLEAN is true. If it is, then the LOG_BOOLEAN is set to false. Every time the user logs in the value of the sharedpreference LOG_COUNT is increased. If it is 5, then I display the dialog box asking to rate and set it back to 0 if the user doesn't rate the app.
But every time the user logs in, the LOG_BOOLEAN is true and LOG_COUNTis 0 though I set it to false and increment it on the first login.
I use a class SessionManager to store and change sharedpreferences.
This is SessionManager.java:
package com.prematixsofs.taxiapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
/**
* Created by admin on 05-01-2016.
*/
public class SessionManager {
SharedPreferences pref;
String userName;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
int loginCount;
private static final String PREF_NAME = "TaxiPref";
private static String LOGIN_BOOLEAN = "loginBoolean";
private static String IS_LOGIN = "IsLoggedIn";
private static String LOG_COUNT = "loginCount";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
public static final String KEY_NAME = "name";
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String name, String email) {
// Storing login value as TRUE
// Storing email in pref
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putBoolean(IS_LOGIN, true);
// commit changes
editor.commit();
}
public void setLoginCount(int count) {
if (count == 0) {
editor.putInt(LOG_COUNT, count);
editor.commit();
} else {
loginCount = pref.getInt(LOG_COUNT, 10);
editor.putInt(LOG_COUNT, loginCount + 1);
editor.commit();
}
}
public int getLoginCount() {
return pref.getInt(LOG_COUNT, 11);//random default value
}
public void setLoginSessionToTrue() {
editor.putInt(LOG_COUNT, 0);
editor.commit();
editor.putBoolean(LOGIN_BOOLEAN, true);
editor.commit();
}
public boolean getLoginBoolean() {
boolean bool;
bool = pref.getBoolean(LOGIN_BOOLEAN, true);
return bool;
}
public void setLoginBooleanToFalse() {
editor.putBoolean(LOGIN_BOOLEAN, false);
editor.putInt(LOG_COUNT, 0);
editor.commit();
boolean set = pref.getBoolean(LOGIN_BOOLEAN, false);
int cou = pref.getInt(LOG_COUNT, 100);
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public String getUserName() {
HashMap<String, String> user = new HashMap<String, String>();
// user email id
return pref.getString(KEY_NAME, null);
}
public String getUserEmail() {
return pref.getString(KEY_EMAIL, null);
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* *
*/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
This is login:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//databaseHelper.delete();
item = databaseHelper.getLogin(uname.getText().toString(), pass.getText().toString());
if (item) {
sessionManager.createLoginSession(databaseHelper.getUserName(uname.getText().toString()), uname.getText().toString());
int c = sessionManager.getLoginCount(); // the value here is 11,the random default value.not the incremented value
countCheck = sessionManager.getLoginBoolean();
if (countCheck) { //check if first time log in
sessionManager.setLoginBooleanToFalse();
uname.setText("");
pass.setText("");
sessionManager.setLoginCount(0);
Intent intent2 = new Intent(getApplicationContext(), DateVehiclePicker.class);
startActivity(intent2);
} else if (sessionManager.getLoginCount() == 5) {
Intent intent1 = new Intent(getApplicationContext(), DateVehiclePicker.class);
sessionManager.setLoginCount(0);
intent1.putExtra("login", true);
startActivity(intent1);
}
} else
uname.setError("Enter a valid Email & Password");
}
});
This is Register.java where I set the sharedpreference to true and assign LOG_COUNTto zero:
signup.setOnClickListener(new View.OnClickListener() {
sessionManager.setLoginSessionToTrue();
});
try like this
private SharedPreferences.Editor getEditor() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
return settings.edit();
}
and then
public void setUserId(String userId) {
this.userId = userId;
getEditor().putString(userIdKey, userId).commit();
}
you should create default initialization
private void initSharedPreference() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
userId = settings.getString(userIdKey, ""); // to avoid nullpointerexception
}
call this method in you SharedPref constructor
EDIT
Create SharedPref like this:
public class SharedPref {
private Context mContext;
private String userId;
private final static String GENERAL_PREFERENCE = "general_pref";
private String userIdKey = "userIdKey";
public SharedPref(Context context) {
this.mContext = context;
initSharedPreference();
}
private void initSharedPreference() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
userId = settings.getString(userIdKey, "");
}
private SharedPreferences.Editor getEditor() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
return settings.edit();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
getEditor().putString(userIdKey, userId).commit();
}
}
when create handler class:
public class DataSourceController {
public SharedPref sharedPref;
private static DataSourceController sInstance;
private DataSourceController(Context context) {
sharedPref = new SharedPref(context);
}
public static synchronized DataSourceController getInstance() {
return sInstance;
}
public static DataSourceController initSingleton(Context context) {
if (sInstance == null) {
sInstance = new DataSourceController(context);
}
return sInstance;
}
public static SharedPref getSharedPreference() {
return getInstance().sharedPref;
}
}
initialize this handler class in your Application class like this:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
DataSourceController.initSingleton(this);
}
}
so now you can call DataSourceController.getSharedPreference().getUserId(); and DataSourceController.getSharedPreference().setUserId("id"); from any place of your app.