I'm making an app for my final project in school..
I've made an Login page and inside the login page I need to retrieve a data from a specific column named Permissions and then check the permission to declare to which next Activity the app will take the user..
In simple words I need something like this:
public void login(View view){ //button
if(Permission == admin){ // get the permission from the user that is logging in.. lets say from username = "Bob123"
//do something..
}
}
A possible solution is to:
create an instance of BackendlessUser in your application class:
public static BackendlessUser user;
If you have added the permission column to the Users table and you have made the email an identity column in the schema you can use the following code to retrieve a BackendlessUser object and direct the user to the correct Activity based on his permission in the Users table:
public void login(String emailToLogin){
DataQueryBuilder dataQueryBuilder = DataQueryBuilder.create();
dataQueryBuilder.setWhereClause("email = " + "'" + emailToLogin + "'");
Backendless.Data.of(BackendlessUser.class).find(dataQueryBuilder,
new AsyncCallback<List<BackendlessUser>>() {
#Override
public void handleResponse(List<BackendlessUser> response) {
if (response.get(0).getProperty("permission").equals("permissionOne")) {
Intent intent = new Intent(LoginActivity.this, permissionOneActivity.class);
startActivity(intent);
}//end if
else if (response.get(0).getProperty("permission").equals("permissionTwo")) {
Intent intent = new Intent(LoginActivity.this, permissionTwoActivity.class);
startActivity(intent);
}//end else if
}//end handleResponse
#Override
public void handleFault(BackendlessFault fault) {
//add error handling here...
}//end handleFault
});}
In the code mentioned below, the response.get(0) will always return the correct user since we are getting the BackendlessUser object based on his email that we set to be a Unique Identifier.
"permissionOne" and "permissionTwo" is whatever you have called your permissions, eg. "permissionOne" takes you to the admin Activity and "permissionTwo" takes you to the clients Activity.
response.get(0).getProperty("permission").equals("permissionOne")
This code myUserObject.getProperty("myColumnName"); retrieves any property you want from the Users table in Backendless
Hope this helps somebody.
Related
Register Button in Register Acvtivity
public void registerBtnClicked(View view){
String email = binding.userEmailEditText.getText().toString();
String password = binding.userPasswordEditText.getText().toString();
String userNameData = binding.usernameEditText.getText().toString();
user = new Users(userNameData,email,password);
db = FirebaseDatabase.getInstance();
databaseReference = db.getReference(Users.class.getSimpleName());
databaseReference.push().setValue(user);
if(email.equals("") || password.equals("")){
Toast.makeText(this, "Enter email and password", Toast.LENGTH_LONG).show();
}else{
auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(RegisterPage.this, MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterPage.this, e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
I created a real time database.But I couldn't figure out how to show username in navigation header section. Can you help me?
If I understand correctly, the firebaseUser is null when you're trying to read the display name from it. This is actually a common scenario, as the user's sign-in session is managed by Firebase in the background, and the current user may change at any time.
The simple fix is to check whether there is a current user before accessing their display name, which you can do with:
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
navUserEmail.setText(firebaseUser.getEmail());
navUserName.setText(firebaseUser.getDisplayName());
}
Note though that the display name is an optional property of the user profile, so it can indeed be null. If you want to display nothing in that case, you can do:
String displayName = firebaseUser.getDisplayName();
navUserName.setText(displayName != null ? displayName : "");
Even if you've set the display name of a user, it may take up to an hour until that is updated for all connected clients, as they all cache the user profile. And since such updates happen in the background... 👇
To correctly handle all auth state changes, you'll want to use an auth state listener, as shown in this article: https://stackoverflow.com/collectives/google-cloud/articles/68104924/listen-for-authentication-state-in-android
I want to add a feature in my app that allows the admin account to delete firebase user accounts from inside the app. I have the user Id that I want to delete stored in a String but can't get the user record from the firebase auth database using the Id.
The getUser() method stays in red and android studio shows a note :
Cannot resolve method getUser(java.lang.String).
I already tried searching on the net for previous similar problems but they were all trying to delete the connected user and not a specific user of a given ID
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
final String UserId = myIntent.getStringExtra("uid"); // will return "User Id"
final Button btnDelete = findViewById(R.id.deleteaccount);
final FirebaseUser userToDelete = FirebaseAuth.getInstance().getUser(UserId);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userToDelete.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(TAG, "Account deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TAG, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
})
}
});
I want to achieve one goal: Being able to delete a user with a given Id.
The Firebase web and mobile client libraries don't support the ability to get and delete user accounts, as that would pose a security risk. The only way to programmatically manage user accounts is using the Firebase Admin SDK to on a backend you control.
I'm trying to make a error checking log in activity, where it will trigger an intent if it detects the following issues :
1) if user hasn't signed up (the email he used isn't authenticated with firebase) which is working out well for me
2) if user has signed up but didn't give me any information into the firebase database
My issue is that, for some reason the code i use to check for information in database, works for users even though they have information in the database attached to their UID.
meaning that the intent to tell them to give information will trigger when they already have given information.
if(task.isSuccessful()){
// Checks if user has submitted information in the Essential Information activity
//Takes the Unique ID(if it is present if not it will tell him to sign up or invalid email) asks the firebase database if he has given information to the database
reference.child("Users").child(UserUID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// User exists
if (dataSnapshot.exists()) {
//Displays Toast telling user that their information is saved in the database
Toast.makeText(LogInActivity.this, "You have data in our database ", Toast.LENGTH_SHORT).show();
}
//User doesn't have information in the database
else {
// Displays Toast telling user he/she needs to sign in into the firebase database
// User goes to UserInformationActivity to give his/her information
Toast.makeText(LogInActivity.this, "You need to give Essential Information", Toast.LENGTH_SHORT).show();
// 3 second delay
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Goes to UserInformationActivity
Intent GoToUserInformation = new Intent(LogInActivity.this, UserInformationActivity.class);
LogInActivity.this.startActivity(GoToUserInformation);
}
}, 3000);
}
}
// if the checking got cancelled, likability of that happening is small
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Don't you want to check if the user is signed in?
Directly from firebase...
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
// check a snapshot to see if there is information....if not, error out.
} else {
// No user is signed in
}
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 have created an application which needs sign in from Facebook/Twitter/Google to get started. In a layout I have created three switches each for Facebook, Twitter and Google which has options ON and OFF. I want to make the switch of the particular account as 'ON' if the user is logged in from that corresponding account. Example if the user is logged in from Facebook, only the switch beside Facebook should be ON. How can I do that?
Any suggestions would be appreciated, and also if somebody know then please refer me to any tutorial related to this.
Below is my code for the login page. I have shown the login for Facebook part:
Thanx :)
private OnClickListener loginButtonListener = new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick( View v ) {
String[] permissions = { "offline_access", "publish_stream", "user_photos", "publish_checkins","photo_upload" };
if(v.getId() == R.id.button1 )
{
facebookSwitch = true;
twitterSwitch = false;
googleSwitch = false;
if( !mFacebook.isSessionValid() ) {
Toast.makeText(Login.this, "Authorizing", Toast.LENGTH_SHORT).show();
mFacebook.authorize(Login.this, permissions, new LoginDialogListener());
}
else {
Toast.makeText( Login.this, "Has valid session", Toast.LENGTH_SHORT).show();
try {
JSONObject json = Util.parseJson(mFacebook.request("me"));
//Log.d("Login", "11111111111111111");
String facebookID = json.getString("id");
//Log.d("Login", "22222222222222");
String firstName = json.getString("first_name");
//Log.d("Login", "3333333333333333333");
String lastName = json.getString("last_name");
//Log.d("Login", "4444444444444444444444");
Toast.makeText(Login.this, "You already have a valid session, " + firstName + " " + lastName + ". No need to re-authorize.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login.this,MainActivity.class);
startActivity(intent);
}
catch( Exception error ) {
Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error ) {
Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Try it this way....
- First create a Singleton Class with 3 booleanvariables for 3 logins info, and thereGetter-Setter`. Singleton is needed over here so that only One object of that class is formed no matter from where that class is called in the whole application. So now you have a single point of info.
- Always check Singleton Class's variables in the beginning of another Activity or when needed by you, to know that whether the user is logged into one or two or all the social networking sites.
////////////////////////////////Edited Part/////////////////////////////
A simple way of creating a Singleton is below, thought there are few more:
public class Test{
public static Test uniqueInstance = new Test();
private Test(){}
public static Test getInstance(){
return uniqueInstance;
// No matter what but always u will get the same instance.
}
}
Now To call this object in another class do as below...
public class Main{
Test t = Test.getInstance(); // Now use t to call the fields and methods of class T.
}