I managed to integrate twitter digits and the authentication is working, but I want to check if the user already added his number and code.
For now I only have the authentication part:
final TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Crashlytics(), new Twitter(authConfig));
And the button event:
digitsButton = (DigitsAuthButton) findViewById(R.id.auth_button);
digitsButton.setCallback(new AuthCallback() {
#Override
public void success(DigitsSession session,
String phoneNumber) {
// Do something with the session
Toast.makeText(WelcomeActivity.this,"Registration Successful",Toast.LENGTH_SHORT).show();
}
#Override
public void failure(DigitsException exception) {
// Do something on failure
Toast.makeText(WelcomeActivity.this,"Registration Failed",Toast.LENGTH_SHORT).show();
}
});
-
How can I check if the user already made these steps?
You can save the fact that an authentication was successful by storing the data somewhere. Storage Options
Using SharedPreferences, to check if an authentication was successful you would use isAuthenticated below:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean isAuthenticated = settings.getBoolean("ALREADY_AUTHENTICATED", false);
And to set that an authentication was successful (true), you could put this in the callback's success method
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("ALREADY_AUTHENTICATED", true /** or false */);
// Commit the edits!
editor.commit();
Related
I am trying to save a boolean into shared preferences with a value of true but when I log it I keeping seeing it returning a false value. Please see the code below and also bear in mind that this code is within a fragment.
SharedPreferences AppPreferences = getActivity().getSharedPreferences("myPrefs", Activity.MODE_PRIVATE);
boolean propertyManagerLoggedIn = AppPreferences.getBoolean(PROPERTYMANAGER_LOGGEDIN, false);
if(!propertyManagerLoggedIn)
{
SharedPreferences.Editor editor = AppPreferences.edit();
transitionInterface.showDashboardIcons();
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
//boolean vlaue = prefs.getbooleanflag(context, false);
Log.d("tag",""+propertyManagerLoggedIn);
}
else
{
Log.d("tag",""+propertyManagerLoggedIn);
}
and below is the relevant lines of code from my AppPreferences class
public final static String PROPERTYMANAGER_LOGGEDIN = "PROPERTYMANAGER_LOGGEDIN";
public static boolean propertyManagerLoggedn(Context context)
{
TinyDB settings = new TinyDB(context);
return settings.getBoolean(AppPreferences.PROPERTYMANAGER_LOGGEDIN);
}
every time you call edit() a new Editor is being returned to you. Accordingly to the documentation
Create a new Editor for these preferences, through which you can make
modifications to the data in the preferences and atomically commit
those changes back to the SharedPreferences object.
so you can either do
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true).commit();
or
editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
but calling putBoolean on an instance and commit on an other won't probably help
You are calling commit on a different instance.
Basically AppPreferences.edit() will give you a new instance.
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
This is another instance in which you are putting the boolean value.
Use the same instance which you have created.
Your code should look like this:
SharedPreferences.Editor editor = AppPreferences.edit();
transitionInterface.showDashboardIcons();
editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
I am trying to finish up the implementation of a login screen for my app. I have a REST API backend that verifies the username + token and returns the userId of the person logging into the app.
I want to store the last userId from the user who has logged into the app. I plan to use Shared preferences for this.
Based on the last stored userId, i plan to execute either going to the main activity (if this user has logged in previously, but logged out after a while and is re-logging in), or executing an AsynkTask to syncronise some data from the backend (if it is a new user). Here is my logic, which seems to not be working properly.
It is switching directly to the MainSyncTask, even if i'm logging in with the last username (userId is the same, received from the API), and savedUserId.equals(currentUserId) should return true and execute the Intent. last userId is properly store in the sharedpreferences db, check with Stecho .
String userId = getUserIdFromAPIResponse();
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
private void checkIdAndGoToActivity() {
final String PREF_VERSION_CODE_KEY = "user_id";
// Get current version code
String currentUserId = userId;
// Get saved version code
String savedUserId = sharedpreferences.getString(PREF_VERSION_CODE_KEY, "");
if (savedUserId.equals(currentUserId)) {
Log.e(TAG, "Current User Logged in");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
/* destroys activity , prevents user from going back to previous MainActivity after login out */
finish();
} else if (!savedUserId.equals(currentUserId)) {
Log.e(TAG, "New user logged in");
MainSyncTask mainSyncTask = new MainSyncTask(LoginActivity.this, LoginActivity.this, userEmail, userPassword);
mainSyncTask.execute();
SyncEventReceiver.setupAlarm(getApplicationContext());
}
// Update the shared preferences with the current version code
sharedpreferences.edit().putString(PREF_VERSION_CODE_KEY, currentUserId).apply();
}
I'm developing an Android app which uses Facebook Login. Login's working fine and I'm able to get back info via Facebook Graph API calls.
I'm trying upload a string to my Firebase database and the string (titled parentFirstNameFromFacebook) is the first name of the user who signed into Facebook. I'm trying to eventually upload a parent object with parentFirstNameFromFacebook in its setName() method.
doneCreatingNameAndPasswordFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gettingTextFromNameAndPasswordEditTexts();
//region creating new Parent object and setting required variables
Parent coOpCreatingParent = new Parent();
coOpCreatingParent.setCoopCreator(true);
coOpCreatingParent.setNumOfHoursOwned(0);
Bundle params = new Bundle();
params.putString("fields", "id,first_name");
new GraphRequest(AccessToken.getCurrentAccessToken(), "me", params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
JSONObject data = response.getJSONObject();
parentFirstNameFromFacebook = data.getString("first_name");
SharedPreferences fBookSharedPref;
SharedPreferences.Editor editor;
fBookSharedPref = getSharedPreferences(Constants.FBOOK_NAME_SHARED_PREF, Context.MODE_PRIVATE);
editor = fBookSharedPref.edit();
editor.putString(Constants.FBOOK_NAME_SHARED_PREF, parentFirstNameFromFacebook);
editor.apply();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
SharedPreferences fBookSharedPref = getSharedPreferences(Constants.FBOOK_NAME_SHARED_PREF, Context.MODE_PRIVATE);
fbookFirstNameForUpload = fBookSharedPref.getString(Constants.FBOOK_NAME_SHARED_PREF, null);
coOpCreatingParent.setName(fbookFirstNameForUpload);
getProfileImageUrlFromFBookGraph();
coOpCreatingParent.setImageUrl(parentImageIDFromFBookGraph);
ArrayList<Child> newChildArrayList = new ArrayList<>();
coOpCreatingParent.setChildren(newChildArrayList);
//endregion
//region creating new ArrayList<Parent> adding Parent object from above
ArrayList<Parent> coOpParentArrayList = new ArrayList<>();
coOpParentArrayList.add(coOpCreatingParent);
//endregion
getReferenceOfCoOpBeingCreated();
//region uploading entire new Co-Op object to Firebase
CoOp coOpObjectBeingUploaded = new CoOp(coOpKey, enteredNewCoOpPassword, enteredNewCoOpName, coOpParentArrayList);
referenceOfCoOp.setValue(coOpObjectBeingUploaded);
//endregion
//region going to AddChildren Activity with Co-Op key in intent
Intent intentForNewActivity = new Intent(getBaseContext(), AddChildrenActivity.class);
intentForNewActivity.putExtra(Constants.CO_OP_REFERENCE_TO_CHILD_ACTIVITY_KEY, coOpKey);
startActivity(intentForNewActivity);
//endregion
}
});
In the Firebase screenshot below, parentsInCoOp is an ArrayList and the 0 below it is the Parent object. I'm trying to set a name and Facebook URL string as other variables for that Parent object.
Firebase screenshot
Whatever I do, the name doesn't show up on Firebase! I'm not sure what I'm doing wrong!
I also tried using Shared Preferences in case there's an issue with setting parentFirstNameFromFacebook within the Facebook call's onCompleted() method. I put parentFirstNameFromFacebook in SharedPref and then got it out to pass it through parent.setName().
Once I successfully upload the first name, then I'll do the same process for the fbook image URl string.
Anyone have any advice? Thanks!
You are performing the Facebook API GraphRequest using the executeAsync() method. The request is processed on a separate thread and the onComplete() response is received asynchronously. I don't use the Facebook API, but am guessing the request requires communication with the Facebook servers and will require many milliseconds to deliver a response.
The result is that these statements
fbookFirstNameForUpload =
fBookSharedPref.getString(Constants.FBOOK_NAME_SHARED_PREF, null);
coOpCreatingParent.setName(fbookFirstNameForUpload);
execute before the statements in the callback have executed and stored the name in preferences.
I have two different app,i have user database in backend,if any user loged in one app,he can also login in the another app without pressing login,just like facebook,how can i implement SSO in app?
You can do that using Content Provider also you can do the same using Shared preferences
Using Shared preferences here is the example:
Call this method when user logged in one app.
public void writeSSOInfo(){
SharedPreferences prefs = getSharedPreferences("CheckSSO",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
if(userLoggedIn){
editor.putBoolean("isLoggedIn", true);
}else{
editor.putBoolean("isLoggedIn", false);
}
editor.commit();
}
After saving in shared memory you can access the same detail in another application using below method.
public void readSSOInfo(){
Context con;
try {
con = createPackageContext("com.app.packagename1", 0);
SharedPreferences pref = con.getSharedPreferences("CheckSSO", Context.MODE_PRIVATE);
dataShared = pref.getBoolean("isLoggedIn", false);
}
catch (Exception e) {
Log.e("Not data shared", e.toString());
}
}
My advice would be after you logged in with any of the apps, I would store a user token with in SharedPreferences between both apps. Then get it at onCreate method of the both apps like this:
String PACKAGE_NAME = "your.package";
String PREFERENCE_NAME = "user-token";
String USER_TOKEN = "";
try {
myContext = createPackageContext(PACKAGE_NAME,Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPrefs = myContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_WORLD_READABLE);
USER_TOKEN = sharedPrefs.getString(PREFERENCE_NAME, "");
}
catch (NameNotFoundException e) {
e.printStackTrace();
}
Then check if USER_TOKEN is empty or not and if it is not I would skip to next screen and keep using same Auth token.
when case is successful i want to edit the variable value and then i want to use this value in other class of my project.
how can i do it?
kindly suggest me?
switch (status) {
case SUCCESSFUL:
SamplePurchasingListener.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_WORLD_READABLE).edit();
editor.putBoolean("PREMIUM", true); // Storing boolean - true/false
editor.commit();
}
});
final Receipt receipt = response.getReceipt();
iapManager.setAmazonUserId(response.getUserData().getUserId(), response.getUserData().getMarketplace());
Log.d(TAG, "onPurchaseResponse: receipt json:" + receipt.toJSON());
iapManager.handleReceipt(response.getRequestId().toString(), receipt, response.getUserData());
iapManager.refreshLevel2Availability();
break;
case ALREADY_PURCHASED:
Log.i(TAG,
"onPurchaseResponse: already purchased, you should verify the entitlement purchase on your side and make sure the purchase was granted to customer");
break;
If you just want to retrieve value from another class, why don't just get it from preferences? Something like this:
SharedPreferences sp = getSharedPreferences(MY_PREFS_NAME, MODE_WORLD_READABLE);
boolean premium = sp.getBoolean("PREMIUM", false);
if(premium) { ...
If there are not value have been stored before, method will return "false".
Maybe I haven't understood your question.