Can't get ApplicationContext in Espresso tests - android

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.

Related

android sharedpreferences get null when app or phone restart

I have a sharedpreferences which save and retrieve data correct. but problem is this when phone restart it give null value.
here is code which I have try
if(encodedImage_profile3!=null)
{
wallpaper_sharedprefrences_profile3 = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = wallpaper_sharedprefrences_profile3.edit();
edit.putString(PROFILE2_WALLPAPER, encodedImage_profile3);
edit.commit();
// Toast.makeText(context, "new same image in prefrences", Toast.LENGTH_SHORT).show();
}
wallpaper_sharedprefrences_profile3 = PreferenceManager.getDefaultSharedPreferences(context);
final String load_wallpaper_profile3 =wallpaper_sharedprefrences_profile3.getString(PROFILE2_WALLPAPER, "");
I have also try this
if(encodedImage_profile3!=null)
{
wallpaper_sharedprefrences_profile3 = context.getSharedPreferences(PREF_PROFILE2_WALLPAPER, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = wallpaper_sharedprefrences_profile3.edit();
edit.putString(PROFILE2_WALLPAPER, encodedImage_profile3);
edit.commit();
}
wallpaper_sharedprefrences_profile3 = context.getSharedPreferences(PREF_PROFILE2_WALLPAPER, Context.MODE_PRIVATE);
final String load_wallpaper_profile3 =wallpaper_sharedprefrences_profile3.getString(PROFILE2_WALLPAPER, "");
Rather than hard-coding shared preference logic , create a Utility class like following and access it throughout your project. Separate methods are available for different data types
/**
* Shared preference class to handle app's local content
*/
public class SharedPreferenceHandler {
//Class variables
private SharedPreferences sharedPrefSettings;
private SharedPreferences.Editor editor;
private static SharedPreferenceHandler m_cPrefObj=null;
private SharedPreferenceHandler(Context context){
sharedPrefSettings = context.getSharedPreferences(SharedPreferenceConstants.SHARED_PREF_KEY, Context.MODE_PRIVATE);
editor=sharedPrefSettings.edit();
}
public static SharedPreferenceHandler getSharedPrefInstance(Context context){
if(m_cPrefObj==null){
m_cPrefObj=new SharedPreferenceHandler(context);
}
return m_cPrefObj;
}
/**
returns string value for shared preference key
*/
public String getSharedPrefValue(String key){
return sharedPrefSettings.getString(key,null);
}
/**
returns boolean shared preference value for key
*/
public boolean getSharedPrefValueBool(String key){
return sharedPrefSettings.getBoolean(key, false);
}
/**
sets string shared preference value for key
*/
public void setSharedPrefBool(String key,boolean value){
editor.putBoolean(key,value);
editor.commit();
}
/**
sets string shared preference value for key
*/
public void setSharedPref(String key,String value){
editor.putString(key, value);
editor.commit();
}
/**
*
* #param key
* #return
*/
public long getSharedPrefValueLong(String key){
return sharedPrefSettings.getLong(key,0);
}
/**
*
* #param key
* #param value
*/
public void setSharedPrefLong(String key,long value){
editor.putLong(key,value);
editor.commit();
}
/**
*
* #param key
* #return
*/
public int getSharedPrefValueInt(String key){
return sharedPrefSettings.getInt(key,0);
}
/**
*
* #param key
* #param value
*/
public void setSharedPrefInt(String key,int value){
editor.putInt(key,value);
editor.commit();
}
}
Inorder to access this logic in required classes,
private SharedPreferenceHandler mSharedPreferenceHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initiateDependencies();
}
/**
* Should initiate classes and objects which will be referred throughout app
*/
private void initiateDependencies(){
mSharedPreferenceHandler =SharedPreferenceHandler.getSharedPrefInstance(this);
}
To set shared preference value do the following
mSharedPreferenceHandler.setSharedPref("PREF_KEY_REFRESH_INTERVAL", "abc");
mSharedPreferenceHandler.setSharedPrefBool("PREF_KEY_REFRESH_ACTION",true);

How to make SingletonClass of Sharedpreference in 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

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.

importing value to another class

btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
return name; //<-here is the error
}
i want to import "name" to another class.. How Can i do this?
I guess you want to send the value to another activity, right? Then you should use intents.
In your activity:
Intent intent = new Intent();
intent.putExtra("name", name);
startActivity(intent);
In the activity where you want to get the value:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String data = extras.getString("name");
Easiest way to do it is via intents.
You can set up an intent for the class you want to launch. Then you can put the name as extra and start the activity class.
Intent intent = new Intent(this,YourActivityClass.class);
intent.putExtra("Name","value");
startActivity(intent);
You can also use preference to store and retrieve datas wherever you need.
For eg: this is in Utils class.
private Editor mEditor;
private SharedPreferences mPreferences;
private static final String PREFERENCE_NAME = "pref";
public Utils(Context context) {
mPreferences = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
mEditor = mPreferences.edit();
}
/**
* Store string in preference.
*
* #param key
* the key
* #param value
* the value
*/
public static void storeStringInPreference(String key, String value) {
mEditor.putString(key, value);
mEditor.commit();
}
/**
* Gets the string from preference.
*
* #param key
* the key
* #return the string from preference
*/
public static String getStringFromPreference(String key) {
return mPreferences.getString(key, null);
}
In Activity A:
String password = inputPassword.getText().toString();
Utils.storeInPreference("password",password); //key,value
In Activity B:
String password = Utils.getStringFromPreference("password"); //key

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