I am using social auth for integration of social app like facebook, google and many more. I successfully authorized and access token is printed in logcat but i want to store them for send to api.
class SignUp extends Activity
{
SocialAuthAdapter adapter;
public void onCreate(Bundle SavedBundleInstanceState )
{
adapter = new SocialAuthAdapter(new ResponseListener());
adapter.authroize(SignUp.this,Provider.Facebook);
}
By This code i get the access token in logcat but dont know how to store it.
you can go with most easiest way shared preferences .. or use session... where you can save and retrieve string with key value..
SessionManager.java
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "wlm";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
private static final String STATUS = "status";
private static final String STATUS_COLOR = "status_color";
// 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";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
/**
* 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, LoginScreen.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 HashMap<String, String> getUserDetails(){
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));
// return user
return user;
}
/**
* 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, LoginScreen.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);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
in you activity you can store you string with
session.editor.putInt("your key", YourString);
and retrieve with
String str = session.pref.getString("your key", "");
also define key for every entry in SessionManager like
private static final String ANY_NAME= "your key";
Acess token is stored in Session class
Session session = Session.getActiveSession();
String accessToken = session.getAccessToken();
Related
I am saving my UserId on SharedPreference for future use. But that data getting cleared if I close that app or kill the app.
code used to save:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = app_preferences.edit();
editor.clear();
editor.putString("USERID", valu1);
editor.apply();
code to retrieve :
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
userID = app_preferences.getString("USERID", "");
Any suggestions?
The apply() method is asynchronous and works on a background thread. It caches the data in RAM and waits until it has sufficient resources to write the data to permanent storage. Considering this, if you immediately close your app, you might lose data. Unlike apply(), commit runs on the UI thread and synchronously, do it has a guaranteed write but pauses the UI thread for a moment. The wait is insignificant though. Consider using commit() instead of apply() and see if it is helpful.
Make one session manger for that, which is separated class.
public class SessionManager {
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Android_Session";
private static final String IS_LOGIN = "IsLoggedIn";
// User name, Email,Id (make variable public to access from outside)
public static final String KEY_PHONE = "phone";
public static final String KEY_EMAIL = "email";
public static final String KEY_ID = "id";
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session when user login first time call this.
*/
public void createLoginSession(String phone, String email, String id) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_PHONE, phone);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_ID, id);
editor.commit();
}
/**
* Check user is login or not if not.
* This will used in dynamic app where session expired from server sideit will redirect to login page.
*/
public void checkLogin() {
if (!this.isLoggedIn()) {
// user is not logged in then redirect to Login Activity
Intent i = new Intent(_context, Login.class);
// Add flags launch modes
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_ID, pref.getString(KEY_ID, null));
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, Login.class);
// Add Flags (Launch Modes)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
_context.startActivity(i);
}
/**
* Check if user login or not
**/
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
Now to retrieve values like
SessionManager session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
To identify login
SessionManager session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
//ToDo
} else {
}
I implemented code for Session Management day before yesterday It's working properly but now It's giving an error on getString() please check this below code and tell me where I am wrong.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "MaangalPref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_PASSWORD = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_GENDER = "gender";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public SessionManager() {}
Create login session
public void createLoginSession(String name, String email, String gender){
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_PASSWORD, name);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_GENDER, gender);
editor.commit();
}
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(){
if(!this.isLoggedIn()){
Intent i = new Intent(_context, AuthenticActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
Get stored session data
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_GENDER,pref.getString(KEY_GENDER, null));
return user;
}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context, AuthenticActivity.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);
}
}
onCreate method of Fragment Class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session class instance
session = new SessionManager();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email________NewMatches",email);
DATA_URL = "http://192.168.2.110/xp/new_matches.php?matri_id="+email;
Log.e("URL________NewMatches",DATA_URL);
}
I think your are calling empty constructor of SessionManager in tab fragment like
session = new SessionManager();
that you are declared in your SessionManager class
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public SessionManager() {}
so finally use in tab fragment
session = new SessionManager(getContext()); //give context of class
instead of session = new SessionManager();
use below code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session class instance
session = new SessionManager(getContext()); //here you have to change
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email________NewMatches",email);
DATA_URL = "http://192.168.2.110/xp/new_matches.php?matri_id="+email;
Log.e("URL________NewMatches",DATA_URL);
}
and also remove empty constructor from SessionManager for future purpose....
I keep getting the following error when running my Espresso tests:
Attempt to invoke virtual method 'android.content.Context android.app.Instrumentation.getTargetContext()' on a null object reference
#RunWith(AndroidJUnit4.class)
public class TestLogin extends AndroidTestCase {
#Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);
#Test
public void testVerifyCredentials() {
Context context = this.getContext().getApplicationContext();
SharedPreferences prefs = context.getSharedPreferences("current.user", Context.MODE_PRIVATE);
assertTrue(prefs.getBoolean("IsLoggedIn", false));
}
}
I already tried this as an InstrumentationTestCase, and then tried instead to do Context context = this.getInstrumentation().getTargetContext().getApplicationContext(); but that still lead to the NPE.
What am I doing wrong?
The SessionManager class I'm using in my application to manage SharedPrefs:
package com.nullpointexecutioners.buzzfilms.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import com.firebase.client.Firebase;
import com.nullpointexecutioners.buzzfilms.Major;
/**
* Helper class for managing a session (i.e. persistence across launches of the app
*/
public class SessionManager {
private static SessionManager sInstance;
private final SharedPreferences pref;
private final SharedPreferences.Editor editor;
//SharedPref file name
private static final String PREF_NAME = "current.user";
//All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
//Username
public static final String KEY_USERNAME = "username";
//Name
public static final String KEY_NAME = "name";
//Email
public static final String KEY_EMAIL = "email";
//Major
public static final String KEY_MAJOR = "major";
//is an Admin
public static final String IS_ADMIN = "isAdmin";
final Firebase mRef = new Firebase("redacted");
/**
* Constructor for instance of SessionManager
* #param context of session
* #return instance of SessionManager
*/
public static SessionManager getInstance(Context context) {
if (sInstance == null) {
sInstance = new SessionManager(context);
}
return sInstance;
}
/**
* Constructor for SessionManager class
* #param context of session
*/
private SessionManager(Context context) {
pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
editor = pref.edit();
}
/**
* Create login session
* #param username to store in SharedPrefs
* #param name name of a user
* #param email to store in SharedPrefs
* #param major major of a user
* #param isAdmin determines if a user is admin or not
*/
public void createLoginSession(String username, String name, String email, String major, boolean isAdmin) {
/*Store each value into SharedPrefs*/
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
if (major.equals(Major.NONE.toString())) {
editor.putString(KEY_MAJOR, "NONE");
} else {
editor.putString(KEY_MAJOR, major);
}
editor.putBoolean(IS_ADMIN, isAdmin);
//Commit changes to SharedPrefs
editor.apply();
}
/**
* Update the current Session's values
* #param name to update
* #param email to update
* #param major to update
*/
public void updateSession(String name, String email, String major) {
/*Store the updated values into SharedPrefs*/
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
if (major.equals(Major.NONE.toString())) {
editor.putString(KEY_MAJOR, "NONE");
} else {
editor.putString(KEY_MAJOR, major);
}
//Commit changes to SharedPrefs
editor.apply();
}
/**
* Checks if current user is logged in
* If false, the user is redirected to WelcomeActivity to login or register
* #return true or false depending if we're logged in
*/
public boolean checkLogin() {
return pref.getBoolean(IS_LOGIN, false);
}
/**
* Checks if current user is an Admin
* If false, the user won't have access to Admin functions
* #return true or false depending if the user is an Admin
*/
public boolean checkAdmin() {
return pref.getBoolean(IS_ADMIN, false);
}
/**
* Getter for currently logged in user's username
* #return current user's username
*/
public String getLoggedInUsername() {
String username = null;
if (pref.contains(KEY_USERNAME) && pref.getBoolean(IS_LOGIN, false)) {
username = pref.getString(KEY_USERNAME, null);
}
return username;
}
/**
* Getter for currently logged in user's name
* #return current user's name
*/
public String getLoggedInName() {
String name = null;
if (pref.contains(KEY_NAME) && pref.getBoolean(IS_LOGIN, false)) {
name = pref.getString(KEY_NAME, "name");
}
return name;
}
/**
* Getter for currently logged in user's email
* #return current user's email
*/
public String getLoggedInEmail() {
String email = null;
if (pref.contains(KEY_EMAIL) && pref.getBoolean(IS_LOGIN, false)) {
email = pref.getString(KEY_EMAIL, null);
}
return email;
}
/**
* Getter for currently logged in user's major
* #return current user's major
*/
public String getLoggedInMajor() {
String major = null;
if (pref.contains(KEY_MAJOR) && pref.getBoolean(IS_LOGIN, false)) {
major = pref.getString(KEY_MAJOR, null);
}
return major;
}
/**
* Clears session credentials
*/
public void logoutUser() {
//UnAuth from Firebase
mRef.unauth();
//Clear SharedPrefs and set IS_LOGIN to false
editor.clear();
editor.putBoolean(IS_LOGIN, false);
editor.commit();
}
/**
* Getter for accessing the current SharedPrefs
* #return this session's SharedPrefs
*/
public SharedPreferences getPref() {
return pref;
}
}
Did you try this?
InstrumentationRegistry.getInstrumentation().getTargetContext()
If you just want to use getSharedPreferences,
try
Activity activity = mActivityRule.getActivity();
SharedPreferences prefs = activity.getSharedPreferences("current.user", Context.MODE_PRIVATE);
assertTrue(prefs.getBoolean("IsLoggedIn", false));
You can use the following code:
ApplicationProvider.getApplicationContext()
your test's this.getContext() gets the context of your TestLogin class. Use
YourActivity.getApplicationContext();
additionally, i recommend to use sharedpreferences in an application context in your application as well, e.g.:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
and for your test:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(yourActivity.getApplicationContext());
so your shared Preferences are the same within all activities inside your application.
I have one activity in which I store all the details regarding registration of user and what I want is to make a class Singleton and save mobile and password of user and in activity I use those stored data instead of creating every time a new object. How can I do that?
Here is my RegistrationModel where I store user data:
public class CRegistrationSessionManagement {
;
// User name (make variable public to access from outside)
public static final String s_szKEY_MOBILENUMBER = "mobileNumebr";
public static final String s_szKEY_PASSWORD = "pin";
public static final String s_szKEY_EMAILID = "emailId";
// Sharedpref file name
public static final String s_szREGIS_FILE_NAME = "RegistrationData";
// All Shared Preferences Keys
private static final String s_szIS_REGISTERED = "IsRegistered";
public static String mobile;
public SharedPreferences m_Regis_Pref;
// Editor for Shared preferences
public SharedPreferences.Editor m_editor;
// Context
public Context m_Context;
public CRegistrationSessionManagement(Context m_Context) {
this.m_Context = m_Context;
m_Regis_Pref = m_Context.getSharedPreferences(s_szREGIS_FILE_NAME, Context.MODE_PRIVATE);
m_editor = m_Regis_Pref.edit();
}
// Registration Session Management.
public void setRegisteredData(String mobile, String pin, String emailId) {
m_editor.putBoolean(s_szIS_REGISTERED, true);
m_editor.putString(s_szKEY_MOBILENUMBER, mobile);
m_editor.putString(s_szKEY_PASSWORD, pin);
m_editor.putString(s_szKEY_EMAILID, emailId);
m_editor.commit();
}
/**
* checkRegistrtaion() session wil check user Registrtaion status
* If false it will redirect user to Registrtaion page
* Else won't do anything
*/
public boolean checkRegistration() {
if (!isRegistered()) {
Intent i = new Intent(m_Context, CMainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
m_Context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored Registration session data
*/
public HashMap<String, String> getRegistrationDetails() {
HashMap<String, String> user = new HashMap<>();
// user name
user.put(s_szKEY_MOBILENUMBER, m_Regis_Pref.getString(s_szKEY_MOBILENUMBER, null));
// user email id
user.put(s_szKEY_PASSWORD, m_Regis_Pref.getString(s_szKEY_PASSWORD, null));
user.put(s_szKEY_EMAILID, m_Regis_Pref.getString(s_szKEY_EMAILID, null));
// return user
return user;
}
public boolean isRegistered() {
return m_Regis_Pref.getBoolean(s_szIS_REGISTERED, false);
}
}
How can I fetch mobile and password in activity where I want to ...by only creating instance of this class...instead of creating every time a new object of that class.
You can use static method. Instead of public HashMap<String, String> getRegistrationDetails () you can use public static HashMap<String, String> getRegistrationDetails (). So when you want to use your getter. CRegistrationSessionManagement. getRegistrationDetails () . Take a look to this example to know more about static method and their uses. Java: when to use static methods
can any one help me out I really need a solution, I have already search on SO, could not success !
I want to store auto generated user_id which I am receiving from server as a JSON response in my share preference and then again get from share preference to other activity and send as a parameter to server
Here is my login Activity where I am receiving unique user id in JSON response when sending username and pass to server
public void connect(String useremail, String userpassword) throws JSONException, IOException
{
RestClient1 client = new RestClient1(Constants.serverPath + Constants.loginMethod);
client.addParam("email", useremail);
client.addParam("password", userpassword);
client.addHeader("content-type", "application/json");
try
{
String response = client.executePost();
JSONObject jsonResponse = new JSONObject(response);
String jsonData = jsonResponse.getString("code");
String jData = jsonResponse.getString("ResponseStatus");
jsData = jData;
if (jsonData.equals("200"))
{
System.out.println("responseStatus =" + jData);
startActivity(new Intent(LoginMainActivity.this, DashBoardActivity.class));
finish();
}
In the "ResponseStatus" I am geting "Login Succsesfull , user_id=1" from server <**<< want to store this response on Share Preference**
My Basic Session Manager class which is not fully construct for storing response in JSON
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "Apppersonal";
// All Shared Preferences Keys
private static final String KEY_USERID = "user_id";
// public static final String KEY_FULLNAME = "fullName";
// public static final String KEY_EMAIL = "email";
// public static final String KEY_DOB = "dateofbirth";
// public static final String KEY_ADDRESS = "address";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createloginSession(int user_id)
{
// Storing id in pref
editor.putInt(KEY_USERID, user_id);
editor.commit();
}
public HashMap<String, String> getPersonalDetails() {
HashMap<String, String> userPersonal = new HashMap<String, String>();
userPersonal.put(KEY_FULLNAME, pref.getString(KEY_FULLNAME, null));
userPersonal.put(KEY_DOB, pref.getString(KEY_DOB, null));
userPersonal.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
userPersonal.put(KEY_ADDRESS, pref.getString(KEY_ADDRESS, null));
// return user
return userPersonal;
// TODO Auto-generated method stub
// return 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, LoginMainActivity.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);
}
}
After getting the user_id just do the following:
SessionManager mSessionManager = new SessionManager(context);
mSessionManager.createloginSession(user_id);
Put it after extending activity
SessionManager session;
And in your method put this
session.createLoginSession(json.getString(user_id));