Here is my Contacts activity (my main activity):
public class Contacts extends Delegate {
private static final String TAG = "Contacts";
public View listContactsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("token", null);
if(restoredText == null)
{
Intent intent = new Intent(this, SignIn.class);
startActivity(intent);
}
setContentView(R.layout.activity_contacts);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ContactListFragment()).commit();
}
//new InEventAPI(this).execute("");
}
...
...
Here is my SignIn activity:
public SignIn extends Delegate {
...
...
public void personSignInDelegate(HttpResponse response, JSONObject result)
{
if(response != null && result != null)
{
switch(response.getStatusLine().getStatusCode())
{
case 200:
try {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("token", result.get("tokenID").toString());
editor.commit();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 401:
Toast.makeText(this, R.string.toastEmailPasswordIncorrect, Toast.LENGTH_LONG).show();
break;
}
}
else
{
Log.d(TAG, "Something went wrong!");
}
}
When I sign in, it commits on SharedPreferences, but when I close my app and re-open, the String becomes null and my OnCreate intents to SignIn again.
Is something that I'm missing?
Just to avoid doubts, my Delegate class:
public class Delegate extends ActionBarActivity {
protected InEventAPI api;
public Delegate() {}
public void personSignInDelegate(HttpResponse response, JSONObject result) {};
}
The problem is most likely with your use of getPreferences(). From the documentation:
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.
Although both classes extend the Delegate class, they are both unique classes with unique names. This means that getPreferences() in Contacts returns a different SharedPreferenceObject compared to SignIn.
Either use getSharedPreferences(String, int)
Eg.
instead of
getPreferences(MODE_PRIVATE);
change it to
getSharedPreferences ("OneSharedPreference", MODE_PRIVATE);
or override getPreferences() in Delegate so it calls getSharedPreferences() with a unique name.
Alternatively, if you're not using the default SharedPreferences for anything (this is usually used by any PreferenceActivity classes), you can always call
PreferenceManager.getDefaultSharedPreferences() and pass in a Context instance.
Related
I want to clear the data I am getting from SharedPreference, I try the following answer but didn't make my task:
1) how to delete sharedpreferences ,Quit and launch application from first actvity in android
2) clear the value of sharedpreferences
3) Remove Shared preferences key/value pairs
4) SharedPreferences Clear/Save
they are all removing value, after they write data into SharedPreference, like editor.remove and .clear...
I have write data into SharedPreference in Notification Activity Like this:
public static final String PREFS_NAME = "com.example.sociapp";
NotificationAdapter notificationAdapter1 = new NotificationAdapter(NotificationsActivity.this, NotificationList, NKeyList);
RnotificationList.setAdapter(notificationAdapter1);
isthereItem = notificationAdapter1.getItemCount();
Toast.makeText(NotificationsActivity.this, ""+isthereItem, Toast.LENGTH_SHORT).show();
//writing data into SharedPreference
SharedPreferences.Editor editor = settings.edit();
editor.putInt("changingicon",isthereItem);
//editor.commit();
editor.clear();
editor.apply();
And I am getting this int value in MainActivity Like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
// Reading from SharedPreferen
try {
//all I want to refresh below line everytime I start MainActivity.
int ChangeIcon = settings.getInt("changingicon", 0);
if (ChangeIcon == 0)
{
int valuebecomes = 0;
notificationIconSetting(valuebecomes);
}
else
{
int valuebecomes = 1;
notificationIconSetting(valuebecomes);
}
Toast.makeText(MainActivity.this, ""+ChangeIcon, Toast.LENGTH_SHORT).show();
}
catch (ClassCastException e){e.printStackTrace();}
The method I call, when I get int value from SharedPreference:
private void notificationIconSetting(int IconTochange)
{
if (IconTochange == 0) {
navigationView.getMenu().getItem(2).setIcon(R.drawable.notification);
}
else
{
navigationView.getMenu().getItem(2).setIcon(R.drawable.notificationalert);
navigationView.setItemIconTintList(null);
}
}
Actually I am getting an int value greater than 0 when there is a notification in the adapter, and when there is no notification in the adapter the int value is equal to 0, then I am using this value to change the notification icon.
When there is notification:
When there is no notification:
Now the problem is whenever I get a value, it remains the same until I clear app cache or Uninstall and then install again.
All I want to refresh the SharedPreference value every time I start MainActivity.
You want to remove one key/value from shared preference
here's how i do it.
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
Few things to note :
You should create a generic class of Shared Preference Like below
public class SharedPrefs {
private static final String MY_PREFS_NAME = "YOUR-PREFERENCE-NAME";
private static SharedPreferences sharedPreferences;
private String masterKeyAlias;
public SharedPrefs(Context context) {
{
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
try {
sharedPreferences = EncryptedSharedPreferences.create(MY_PREFS_NAME,masterKeyAlias,context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
public String getStrings(Context mContext, String key){
return sharedPreferences.getString(key, null);
}
public void putString(Context mContext, String key, String value ){
sharedPreferences.edit().putString(key, value).apply();
}
public boolean getBoolean(Context mContext, String key){
return sharedPreferences.getBoolean(key, false);
}
public void putBoolean(Context mContext, String key, boolean value ){
sharedPreferences.edit().putBoolean(key, value).apply();
}
public static void clear(Context mContext){
sharedPreferences.edit().remove("user").apply();
}
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
}
Here how to use it
Declaration :
SharedPrefs sharedPrefs;
Initialization :
sharedPrefs = new SharedPrefs(context);
just call the methods you want to use to store value in shared preference like
sharedPrefs.putString(context,key,value)
masterKeyAlias is to secure my Shared preferences.
Add this your app gradle
implementation "androidx.security:security-crypto:1.0.0-beta01"
you can read more about it here Best Practices
sorry for this simple question but im new to this.
I have this code:
public void English (View view) {
if (toggleButton.isChecked()) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("selectedlanguage", "English");
editor.commit();
Toast.makeText(getBaseContext(), sharedPref.getString("selectedlanguage", null) + " is the default page", Toast.LENGTH_SHORT).show();
English();
}
else English();
For later use I want to use the editor.putString("selectedlanguage", "English");"English" as class name.
Like this:
if (sharedPref.getString("selectedlanguage", null) != null) {
//use the "English" as class name so it will execute the class
}
Going off your question and comments, I'm assuming you only want to create a class based off a value stored in SharedPreferences. I'm also assuming you want to create several "languages", and launch the appropriate class from the SharedPreferences value. For that I would use the Factory pattern:
First, create a "language" interface that contains the common methods for all your language classes:
public interface Language {
//Example
void speak();
}
Second, have all your language classes implement this interface:
public class English implements Language {
#Override
public void speak() {
Log.i("Tag", "English");
}
}
public class Chinese implements Language {
#Override
public void speak() {
Log.i("Tag", "Chinese");
}
}
Third, create a Factory class that builds "language" classes:
public class LanguageFactory {
public static final int LANGUAGE_ENGLISH = 100;
public static final int LANGUAGE_CHINESE = 101;
public Language getLanguage(int code) {
Language language = null;
switch (code) {
case LANGUAGE_ENGLISH:
language = new English();
break;
case LANGUAGE_CHINESE:
language = new Chinese();
break;
}
return language;
}
}
Now, whenever you save to shared preferences, use:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("selectedlanguage", LanguageFactory.LANGUAGE_ENGLISH);
editor.commit();
And then, when you want to use the stored value:
int languageCode = sharedPref.getInt("selectedLanguage", -1);
LanguageFactory factory = new LanguageFactory();
Language language = factory.getLanguage(languageCode);
In this case, "language" will be "English", but it will change depending on the "code" you store to SharedPreferences. This is a very flexible system that will allow you to add new languages in the future, and as you use constants there is much less chance of errors caused by providing incorrect values.
Please see this
Class<?> c = null;
if(StringClassname != null) {
try {
c = Class.forName(StringClassname );
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I used to SharedPreferences.apply() method. When this method is called very often, then it hangs the application. Commit() method is very slow, but is working properly.
You can get the ANR in my example. Fold and unfold the activity!
public class Main extends Activity {
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
new Thread(new Runnable() {
#Override
public void run() {
while(true) {
SharedPreferences.Editor ed = getEditor();
ed.putString(getUUID(), getUUID());
ed.apply();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public static String getUUID() {
return UUID.randomUUID().toString();
}
final private String BASE = "BASE";
private SharedPreferences shadPrefBase = null;
SharedPreferences getSharedPreferences() {
if(shadPrefBase == null) {
shadPrefBase = getSharedPreferences(BASE, Context.MODE_MULTI_PROCESS);
}
return shadPrefBase;
}
private SharedPreferences.Editor editorShared = null;
private SharedPreferences.Editor getEditor() {
if(editorShared == null) {
editorShared = getSharedPreferences().edit();
}
return editorShared;
}
}
Fold and unfold the activity!
Every 10 milliseconds, indefinitely, you are forking a background thread via the apply() call, all of which are going to queue up as they attempt to do I/O on the same data. That is not going to give you good results.
Beyond that, I would be very careful about sharing Editor instances across threads the way you are.
Can anybody tell me how to maintain session for a user login. For example when the user sign- in to an application they have to be signed in unless the user logouts or uninstall the application similar to gmail in android.
Make one class for your SharedPreferences
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Now after making this class when you want to use it, use like this: make object of this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
now whenever you want to get the username then same work is to be done for session object and call this
session.getusename();
Do same for password
You can achieve this by using AccountManager.
Code Sample
// method to add account..
private void addAccount(String username, String password) {
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type)); // account name identifier.
if (accounts.length > 0) {
return;
}
final Account account = new Account(username,
getString(R.string.account_type));
accnt_manager.addAccountExplicitly(account, password, null);
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_PASSWORD, password);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
getString(R.string.account_type));
// intent.putExtra(AccountManager.KEY_AUTH_TOKEN_LABEL,
// PARAM_AUTHTOKEN_TYPE);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, "token");
this.setAccountAuthenticatorResult(intent.getExtras());
this.setResult(RESULT_OK, intent);
this.finish();
}
// method to retrieve account.
private boolean validateAccount() {
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
Log.e("calback", "msg");
try {
Bundle b = arg0.getResult();
if (b.getBoolean(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE)) {
//User account exists!!..
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type));
if (accounts.length <= 0) {
return false;
} else {
loginNameVal = accounts[0].name;
loginPswdVal = accnt_manager.getPassword(accounts[0]);
return true;
}
}
I have one simple way rather than maintain a session.
i.e. Just store one boolean variable with your username and password. by default set value equal to false.
After first successful login make its value to true.
Then just check its value on your Mainactivity, if it is true then jump to next activity otherwise jump to login activity.
You can use a boolean value in the SharedPreferences.
Load it before login to check if login is needed.
Save it after login.
Use SharedPreferences.
Code to save a value to sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putInt("value", your_value);
ed.commit();
Code to get value from sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
int value = sp.getInt("value", default_value);
You can check login and logout by using this value.
You can obtain that behaivour in a few different ways, the one I prefer is setting a flag in the shared prefs. whe a user logs in an check it when the app is started if you get the default value the user is not loggend, else you should have your flag (i use the user name) set and avoid the log-in section.
save the user data in shared preferences till the user logs out.
once user logs out clear the data from shared preferences.
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
editor = prefs.edit();
}
public void setusename(String usename) {
editor.putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUcUZxeHo0UnJ5UHc
Fetch Previous Login ID in android
**After Login save Email ID is SharedPreferences**
emaidId = et_Email.getText().toString().trim();
SharedPreferences ss = getSharedPreferences("loginSession_key", 0);
Set<String> hs = ss.getStringSet("set", new HashSet<String>());
hs.add(emaidId);
SharedPreferences.Editor edit = ss.edit();
edit.clear();
edit.putStringSet("set", hs);
edit.commit();
===================onCreate()====================
===================AutoCompleteTextView set Adapter===================
**Fetch PRevious Login Email id in email EditText**
SharedPreferences sss = getSharedPreferences("loginSession_key", 0); // todo loginSession_key key name ALWAYS SAME
Log.i("chauster", "2.set = " + sss.getStringSet("set", new HashSet<String>()));
Log.e("Session", "Value->" + sss.getStringSet("set", new HashSet<String()));
ArrayList<String> al = new ArrayList<>();
al.addAll(sss.getStringSet("set", new HashSet<String>()));
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, al);
//Getting the instance of AutoCompleteTextView
et_Email.setThreshold(1);//will start working from first character
et_Email.setAdapter(adapter);//setting the adapter data into the
Using this class will help you to store all types of sessions
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void set(String key,String value) {
prefs.edit().putString(key, value).commit();
}
public String get(String key) {
String value = prefs.getString(key,"");
return value;
}
}
Through this format, you can set or get multiple objects of data, you don't need to create separate functions to store different models in SharedPreferences.
* Here in this format, you don't need to pass your object KEY for putString() and getString()
* Using the object class name you are able to identify your session object uniquely, for both setModel() and getModel()
public class Session {
private final SharedPreferences pref;
public Session(Context ctx) {
pref = PreferenceManager.getDefaultSharedPreferences(ctx);
//pref = ctx.getSharedPreferences("IDENTIFIED_NAME", Context.MODE_PRIVATE);
}
public <U> void setModel(U obj) {
pref.edit().putString(getClassName(obj), SerializeObject(obj)).apply();
}
/* Parameter Example: Class.class */
public <U> U getModel(Class<U> type) {
String user = pref.getString(type.getSimpleName(), null);
if (isEmptyOrNull(user)) {
return null;
}
return DeserializeObject(user, type);
}
/* The below functions are for support, You can move the below part to your own BaseUtil class. */
public static boolean isEmptyOrNull(String data) {
if (data == null) {
return true;
}
if (data.isEmpty() || data.trim().isEmpty()) {
return true;
}
return false;
}
public static String getClassName(Object obj) {
return obj.getClass().getSimpleName();
}
public static String SerializeObject(Object myObject) {
// serialize the object
try {
Gson gson = new Gson();
String json = gson.toJson(myObject);
return json;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public static <U> U DeserializeObject(String serializedObject, Class<U> type) {
// serialize the object
try {
if (serializedObject == null || serializedObject.isEmpty()) {
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
U data = gson.fromJson(serializedObject, type);
return data;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
Create an object class (file_name: UserModel.java)
public class UserModel {
public String userId;
public String firstName;
public String lastName;
public String email;
public String phone;
}
How to use - For setModel() and getModel()
//creating an instance of the Session class
Session session = new Session(ctx); // Here you have to pass the Context(ctx)
// setting value in the UserModel
UserModel obj = new UserModel();
obj.firstName = "Apu";
obj.lastName = "Pradhan";
obj.email = "godfindapu#gmail.com";
obj.phone = "123456789";
// set UserModel in the Session
session.setModel(obj);
//getting UserModel data from the Session
UserModel userData = session.getModel(UserModel.class);
Currently I'm writing an adapter class to provide a convenient way for communication with the facebook API.
The way I thought about using it is to run the authentication when the app is starting up, downloading user's private picture, and later in the app publishing updates on users facebook wall using an AsyncFacebookRunner.
However flipping through the documentation it seems for every authorize() implementation the first parameter have to be an activity.
void authorize(Activity activity, final DialogListener listener):
And here I begin to wonder.
Thinking about activities and life cycles what will happen when the activity I threw in will be destroyed? Wouldn't the reference for this object Facebook.mAuthActivity become invalid as well.
I see the logout() method "only" asks for a context.
String logout(Context context) throws ...:
context - The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
From what I see I can not guarantee the "login-activity" will still be present as app's uptime increases - actually the opposite is more likely.
Are there any special situations I should consider to prevent the app form total crashing in a later state?
You can try use my FBHelper class.
public class FBHelper {
private SharedPreferences mPrefs;
private Context context;
private final String ACCES_TOKEN = "access_token";
private final String ACCES_EXPIRES = "access_expires";
private Facebook facebook;
private FBHelperCallbacks callback;
public FBHelper(Context context, Facebook facebook)
{
this.context = context;
this.facebook = facebook;
}
public void setSignInFinishListener(FBHelperCallbacks callback)
{
this.callback = callback;
}
public void FacebookSingleSignIn() {
mPrefs = ((Activity)context).getPreferences(Context.MODE_PRIVATE);
String access_token = mPrefs.getString(ACCES_TOKEN, null);
long expires = mPrefs.getLong(ACCES_EXPIRES, 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
/*
* Only call authorize if the access_token has expired.
*/
if(!facebook.isSessionValid()) {
Log.i("Facebook","Facebook session is not valid based on acces token... authorizing again");
facebook.authorize((Activity)context, new String[] {"user_about_me"},new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
callback.onError(e.toString());
}
#Override
public void onError(DialogError e) {
Log.i("Facebook","onError inner");
callback.onError(e.toString());
}
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(ACCES_TOKEN, facebook.getAccessToken());
Log.i("Facebook","Saving acces token:"+facebook.getAccessToken());
editor.putLong(ACCES_EXPIRES, facebook.getAccessExpires());
editor.commit();
callback.onSignedInFinished(facebook.getAccessToken());
}
#Override
public void onCancel() {
callback.onError("onCancel");
}
});
}
else
{
Log.i("Facebook","Accces token read form preferencesno no need to authorize");
callback.onSignedInFinished(facebook.getAccessToken());
}
}
public String LogOut()
{
try {
//set ACCES_TOKEN to null
mPrefs = ((Activity)context).getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(ACCES_TOKEN, null);
editor.putLong(ACCES_EXPIRES, 0);
editor.commit();
return facebook.logout(context);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Error";
}
public static abstract class FBHelperCallbacks{
public abstract void onSignedInFinished(String accesToken);
public abstract void onError(String message);
}
}
This is how you use this class.
public class LogInActivity extends Activity {
private static final String TAG = "LogInActivity";
public static final int REQUEST_CODE = 1;
private Context context;
private Facebook facebook;
private FBHelper fbhelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
this.context = this;
Handler pauser = new Handler();
pauser.postDelayed (new Runnable() {
public void run() {
facebook = new Facebook(context.getString(R.string.FACEBOOK_APP_ID));
fbhelper = new FBHelper(context, facebook);
if (aHelper.isLogedIn())
{
//log out
fbhelper.LogOut();
}
else
{
//facebook login
fbhelper.setSignInFinishListener(fbcallback);
fbhelper.FacebookSingleSignIn();
}
}
}, 100);
}
FBHelperCallbacks fbcallback = new FBHelperCallbacks() {
#Override
public void onSignedInFinished(String accesToken) {
Log.d(TAG,"log in finish");
}
#Override
public void onError(String message) {
setResult(RESULT_CANCELED);
finish();
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
aHelper is object that hold some application specific data. Basically you should decide here if you want to log in or log out.
using facebook API for the android is easy and in your case you don't need to save the Facebook instance the only thing you need is to save the authKey of the facebook on the first login then you can use it anywhere.
this means that you can create more than one instance of the facebook object in mutiple activities based on the authKey.
Otherwise you need to put this facebook object in a singleton handler to save it among the application :
class x {
private Facebook obj;
private static x instance;
private x (){
}
public static x getX(){
if(instance == null){
instance = new x();
}
return instance;
}
public void setIt(Facebook obj){
this.obj = obj;
}
public Facebook getIt(){
return obj;
}
}
but this way is not the best way to implement the code you need to create a Facebook instance for each activity using the authKy.