How to make SingletonClass of Sharedpreference in android - android

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

Related

How to get values from shared preference and check it using if

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

SharedPreference value changes back on every login even with commit()

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.

how to store access token for facebook in social auth

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

Saving user_id responce from JSON to sharepreferance

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

Facebook login through android

I write an Android application that integrates facebook, but failing in the login to facebook step. What I'm doing basically is to perform authorization and then ask if the session is valid. The answer is always negative. If I'm trying a simple request like:
String response = facebookClient.request("me");
I am getting this response:
{"error":{"message":"An active access token must be used to query
information about the current user.","type":"OAuthException"}}
Maybe I have the wrong hash key (through I read pretty good threads how to get it right). I'd like to know if this is a way to insure key is matching.
I based my code on this - Android/Java -- Post simple text to Facebook wall?, and add some minor changes. This is the code:
public class FacebookActivity extends Activity implements DialogListener
{
private Facebook facebookClient;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);//my layout xml
}
public void login(View view)
{
facebookClient = new Facebook("my APP ID");
facebookClient.authorize(this, this);
if (facebookClient.isSessionValid() == true)
Log.d("Valid:", "yes");
else
Log.d("Valid:", "no");
}
}
Note that authorize method is asynchronous.
You should implement an onComplete method of DialogListener and make all the work you need (such as graph API me request) there.
Use following code in your app:
public class FacebookLogin {
private AsyncFacebookRunner mAsyncRunner;
private Facebook facebook;
private Context mContext;
private String mFName;
public static final String[] PERMISSIONS = new String[] {"email", "publish_checkins", "publish_stream","offline_access"};
public FacebookLogin(Context mContext) {
this.mContext=mContext;
facebook=new Facebook(YOUR_APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void Login() {
facebook.authorize((Activity) mContext,PERMISSIONS,Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
}
public void Logout() throws MalformedURLException, IOException {
facebook.logout(mContext);
}
public boolean isValidUser() {
return facebook.isSessionValid();
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
//Save the access token and access expire for future use in shared preferece
String profile=facebook.request("me")
String uid = profile.getString("id");
mFName= profile.optString("first_name");
new Session(facebook, uid, mFName).save(mContext);
}
public void onFacebookError(FacebookError error) {
displayMessage("Opps..! Check for Internet Connection, Authentication with Facebook failed.");
}
public void onError(DialogError error) {
displayMessage("Opps..! Check for Internet Connection, Authentication with Facebook failed.");
}
public void onCancel() {
displayMessage("Authentication with Facebook failed due to Login cancel.");
}
}
}
On Login complete save the facebook access token and access expire in your shared preference and while using again facebook object later set that access token and access expire to facebook object , it will not give the error which occurs in your code.
you can use following class :
public class Session {
private static Session singleton;
private static Facebook fbLoggingIn;
// The Facebook object
private Facebook fb;
// The user id of the logged in user
private String uid;
// The user name of the logged in user
private String name;
/**
* Constructor
*
* #param fb
* #param uid
* #param name
*/
public Session(Facebook fb, String uid, String name) {
this.fb = fb;
this.uid = uid;
this.name = name;
}
/**
* Returns the Facebook object
*/
public Facebook getFb() {
return fb;
}
/**
* Returns the session user's id
*/
public String getUid() {
return uid;
}
/**
* Returns the session user's name
*/
public String getName() {
return name;
}
/**
* Stores the session data on disk.
*
* #param context
* #return
*/
public boolean save(Context context) {
Editor editor =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE).edit();
editor.putString(ConstantsFacebook.TOKEN, fb.getAccessToken());
editor.putLong(ConstantsFacebook.EXPIRES, fb.getAccessExpires());
editor.putString(ConstantsFacebook.UID, uid);
editor.putString(ConstantsFacebook.NAME, name);
editor.putString(ConstantsFacebook.APP_ID, fb.getAppId());
editor.putBoolean(ConstantsFacebook.LOGIN_FLAG,true);
if (editor.commit()) {
singleton = this;
return true;
}
return false;
}
/**
* Loads the session data from disk.
*
* #param context
* #return
*/
public static Session restore(Context context) {
if (singleton != null) {
if (singleton.getFb().isSessionValid()) {
return singleton;
} else {
return null;
}
}
SharedPreferences prefs =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
String appId = prefs.getString(ConstantsFacebook.APP_ID, null);
if (appId == null) {
return null;
}
Facebook fb = new Facebook(appId);
fb.setAccessToken(prefs.getString(ConstantsFacebook.TOKEN, null));
fb.setAccessExpires(prefs.getLong(ConstantsFacebook.EXPIRES, 0));
String uid = prefs.getString(ConstantsFacebook.UID, null);
String name = prefs.getString(ConstantsFacebook.NAME, null);
if (!fb.isSessionValid() || uid == null || name == null) {
return null;
}
Session session = new Session(fb, uid, name);
singleton = session;
return session;
}
/**
* Clears the saved session data.
*
* #param context
*/
public static void clearSavedSession(Context context) {
Editor editor =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
singleton = null;
}
/**
* Freezes a Facebook object while it's waiting for an auth callback.
*/
public static void waitForAuthCallback(Facebook fb) {
fbLoggingIn = fb;
}
/**
* Returns a Facebook object that's been waiting for an auth callback.
*/
public static Facebook wakeupForAuthCallback() {
Facebook fb = fbLoggingIn;
fbLoggingIn = null;
return fb;
}
public static String getUserFristName(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
String frist_name = prefs.getString(ConstantsFacebook.NAME, null);
return frist_name;
}
public static boolean checkValidSession(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
Boolean login=prefs.getBoolean(ConstantsFacebook.LOGIN_FLAG,false);
return login;
}
}

Categories

Resources