I am trying to make an android app. But I got a problem. Every time I log in I want to login like manager or user. I got 1 table in my database for all users. But I want it to be so when I login with the user called "manager" he will see a different screen from all the other users in the table.
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (username == "manager") {
Intent takeUserHome = new Intent(LoginActivity.this, ManagerHomePage.class);
startActivity(takeUserHome);
} else {
Intent takeUserHome = new Intent(LoginActivity.this, UserHomePage.class);
startActivity(takeUserHome);
}
This is mine current code, but when I login with manager I still get to UserHomePage instead of the ManagerHomePage
you are comparing the string references instead on their values. using the == operator as you do in the line
username == "manager"
This compares the references, not the actual string content. what you probably want is :
username.equals("manager")
For a more in depth explenation see: this question.
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'm new with zoom integration.
I wants user login and create meeting in their account. I've done login user part using loginWithZoom method but now wants to create meeting for that auth token needed.
How can I get token when user login in zoom without OAuth?
I've found but not getting much idea. I tried with JWT token it works with
https://api.zoom.us/v2/users/me/meetings api. I gave Authorization token and content-type in
headers. it gives me all meetings of that specific user. but problem to get different authorization token for different users. I don't have idea is it possible or not.
Suggest if anyone knows
Code I've used for Login:
public void initializeSdk(Context context) {
ZoomSDK sdk = ZoomSDK.getInstance();
// TODO: Do not use hard-coded values for your key/secret in your app in production!
ZoomSDKInitParams params = new ZoomSDKInitParams();
params.appKey = "a...t4.."; // TODO: Retrieve your SDK key and enter it here
params.appSecret = "y...19"; // TODO: Retrieve your SDK secret and enter it here
params.domain = "zoom.us";
params.enableLog = true;
// TODO: Add functionality to this listener (e.g. logs for debugging)
ZoomSDKInitializeListener listener = new ZoomSDKInitializeListener() {
/**
* #param errorCode {#link us.zoom.sdk.ZoomError#ZOOM_ERROR_SUCCESS} if the SDK has been initialized successfully.
*/
#Override
public void onZoomSDKInitializeResult(int errorCode, int internalErrorCode) {
Log.i("","onZoomSDKInitializeResult Error code"+errorCode);
Toast.makeText(getApplicationContext()," error code : " + errorCode,Toast.LENGTH_LONG).show();
}
#Override
public void onZoomAuthIdentityExpired() {
System.out.println(" identity expired..");
}
};
sdk.initialize(context, listener, params);
}
findViewById(R.id.login_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "onclick of login", Toast.LENGTH_LONG).show();
Log.i(" ","onclick of login : "+ ZoomSDK.getInstance().isLoggedIn());
if (ZoomSDK.getInstance().isLoggedIn()) {
//wants to create meeting
} else {
createLoginDialog();
}
}
});
private void createLoginDialog() {
new AlertDialog.Builder(this)
.setView(R.layout.dialog_login)
.setPositiveButton("Log in", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
AlertDialog dialog = (AlertDialog) dialogInterface;
TextInputEditText emailInput = dialog.findViewById(R.id.email_input);
TextInputEditText passwordInput = dialog.findViewById(R.id.pw_input);
if (emailInput != null && emailInput.getText() != null && passwordInput != null && passwordInput.getText() != null) {
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
if (email.trim().length() > 0 && password.trim().length() > 0) {
login(email, password);
}
}
dialog.dismiss();
}
})
.show();
}
public void login(String username, String password) {
int result = ZoomSDK.getInstance().loginWithZoom(username, password);
if (result == ZoomApiError.ZOOM_API_ERROR_SUCCESS) {
// Request executed, listen for result to start meeting
ZoomSDK.getInstance().addAuthenticationListener(authListener);
}
}
public void onZoomSDKLoginResult(long result) {
if (result == ZoomAuthenticationError.ZOOM_AUTH_ERROR_SUCCESS) {
// Once we verify that the request was successful, we may start the meeting
Toast.makeText(getApplicationContext(), "Login successfully", Toast.LENGTH_SHORT).show();
} else if(result == ZoomAuthenticationError.ZOOM_AUTH_ERROR_USER_NOT_EXIST || result == ZoomAuthenticationError.ZOOM_AUTH_ERROR_WRONG_PASSWORD){
Toast.makeText(getApplicationContext(),"Invalid username or password",Toast.LENGTH_LONG).show();
}
}
Thanks in advance.
I tried with JWT token it works with
https://api.zoom.us/v2/users/me/meetings api. I gave Authorization
token and content-type in headers. it gives me all meetings of that
specific user. but problem to get different authorization token for
different users. I don't have idea is it possible or not.
Assuming these users are not part of the same Zoom account, then no, it is not possible as of 2021-08-28. JWT-based authentication is only for Zoom integration in internal applications/services:
Note: JWT may only be used for internal applications and processes. All apps created for third-party usage must use our OAuth app type.
In this context, "internal" means "only to be used with a single Zoom account." Note that there can be many users under one account (e.g., all employees of Corporation XYZ are part of XYZ's Zoom account). Put differently, you can use a JWT issued for the XYZ Zoom account to access information for all users under the XYZ Zoom account, but if you need data for users that are not part of the XYZ Zoom account, then you need an API Key and API Secret for their Zoom account(s) as well to generate JWTs that you can use to retrieve their data.
If you are building an integration/service that you want to make available to the general public, then you need to use OAuth:
This app can either be installed and managed across an account by
account admins (account-level app) or by users individually
(user-managed app).
I am using the post comment system in android, I want to create a chat option upon clicking the button only among the post author and comment author only, if anyone else clicks it should not open the chat room.
I am using the below code for the same purpose, but it is not working the way required. you can refer the idea of chat system in stackoverflow, the similar thing I want. the below code is in adapter class linking to the button on the recyclerview item. I am the PostAuthorId and CommentAuthorId are already confirmed, I have to just set the condition if the login user is the same as one of them.
i am using firestore database for the same
if any more information is required do let me know.
commentsViewHolder.chat.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View view) {
if(PostAuthorID == mAuth.getUid() || CommentAuthorId == mAuth.getUid())
{
Toast.makeText(CommentActivity.this, "Hello", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(CommentActivity.this, ChatRoomActivity.class);
intent.putExtra(ChatRoomActivity.CHAT_ROOM_ID, ChatRoomId);
intent.putExtra(ChatRoomActivity.CHAT_ROOM_NAME, ChatRoomName);
startActivity(intent);
}
else
{
Toast.makeText(CommentActivity.this, "You are not authenticated", Toast.LENGTH_SHORT).show();
}
}
});
Probably the problem is that == won't work for strings.
Use PostAuthorID.equals(mAuth.getUid()) to compare strings, not the == operator. mAuth.getUid() returns a String and I am assuming that PostAuthorID is a String too
Like:
if(PostAuthorID.equals(mAuth.getUid()) || CommentAuthorId.equals(mAuth.getUid())){
....
} else {
....
}
Remember:
== operator only compares object references, while the String.equals() method compares both String's values!
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.
In an android app, which uses Parse, the login flow is like this...
We have our own logic to see if the user has entered the correct credentials. Once we verify that, signUpOrLoginOnParse() is called. Parse is used just to store data and handle sessions locally. Users can not access the api without the token.
private void signUpOrLogin(final String username, final String token) {
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(username);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// sign up success. ParseUser.getCurrentUser() populated
saveTokenToCloud(token);
} else if ("condition to check if the user already exists") {
// existing user, login.
ParseUser.logInInBackground(username, username, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
// login was successful, ParseUser.getCurrentUser() populated
saveTokenToCloud(token);
}
});
} else {
showProgress(false);
e.printStackTrace();
}
}
});
}
private void saveTokenToCloud(String token) {
// saving token to cloud
ParseUser user = ParseUser.getCurrentUser();
user.put("token", token); // THIS IS WHERE I GET NULL POINTER EXCEPTION
user.saveEventually();
// link installation to user.
ParseInstallation parseInstallation = ParseInstallation.getCurrentInstallation();
parseInstallation.put("user", user);
parseInstallation.saveEventually();
// Starting next activity
Intent i = new Intent(this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
All good when I first run the app. Once, logout button is pressed (contains - Parse.logoutInBackground()), it shows the LoginActivity (current one). When trying to log in, everything succeeds but I get a NullPointerException at line 3 of saveTokenToCloud().
It says - trying to invoke virtual method .put() over a null object reference.
But, isn't Parse.currentUser() already populated since this method is called from callback of methods that do that ?
It works after restarting the app. But then the same continues if logout is pressed.
After calling logoutInBackground , future calls to getCurrentUser() will return null.
You will need to initialize the user again.
signUpInBackground will create a new ParseUser on the server, and also persist the session on disk so that you can access the user using ParseUser.getCurrentUser().
However i am not sure you should be calling it every single time you log in.
Instead of calling the getCurrentuser inside the saveToken method you can pass the user to the saveTokenMethod from the done callback parameter.
Separate you logic in distinct methods for sign up and logIn. I suggest you check before calling signUp, and not abusing it every time you want to login