I am working on android for parse.com. I have successfully logged in and signed up with my credentials and data is also uploading in my parse.com tables. Code snippet for login is given below:
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Now i need to get the information of current user, kindly mention me the method or changing which i have to do to get the information of current user.
Thanks in advance!
Calling things like user.getObjectId(); or user.getString("username"); is how you get information from the ParseObject.
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
String username = user.getString("username");
String userId = user.getObjectId();
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Once the user is authenticated, open up new activity and you can access current user by using the static method getCurrentUser.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// do stuff with the user
} else {
// show the signup or login screen
}
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.getUsername();
newTable.put("user_name",currentUser );
This is how you can get a user information in your other table (newTable).
Let me know if it helps. :)
With this I got the user info.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null){
String email = currentUser.getEmail();
String username = currentUser.getUsername();
String objectID = currentUser.getObjectId();
} else {
Toast.makeText(getApplicationContext(), "the user does not exist!",Toast.LENGTH_SHORT).show();
}
ParseUser currentUser = ParseUser.getCurrentUser();
String currentUserString = String.valueOf(currentUser.getUsername());
newTable.put("user_name",currentUserString);
For some reason I'm not sure about, you need to cast currentUser to String.
Related
I'm currently working on a parental control application, what I would want to achieve is that the parent and child can login to the system with the same email address on different devices, and I also want to achieve auto login feature, when the parent open the app, it will directly load the ParentActivity, if child then load the ChildActivity.
But now the problem is that I can't do this, I have no idea how to identify both of them since they are using the same email address. Previously, I was able to perform auto login for the parent by using FirebaseAuth.getCurrentUser(), and then check the userType inside firestore. But now I can't check anything to identify whether the user is a child or parent.
What I have tried:
Create a field call "child", when the user (John) login as child, update the field with "TRUE" (let's say), when John quit app and login again, the system will starting checking if userType == "parents", if no then only it will check if child == "TRUE". Therefore, the child user will always be auto login to the ParentActivity but ChildActivity.
Is there any way to achieve this? Hope you guys understand what my problem is. The attached image shows how I achieve auto login for parent previously. Thanks in advance!
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Transparent Status Bar
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
ButterKnife.bind(this);
//FirebaseApp.initializeApp(this.getBaseContext());
firebaseAuth = FirebaseAuth.getInstance();
clearUserType();
}
// Hide keyboard after user clicking somewhere
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#OnClick(R.id.LoginButton)
public void login(){
progressBar.setVisibility(View.VISIBLE);
if (!Utils.isValidEmail(email, emailLayout) | !Utils.hasEmail(email, emailLayout) | !Utils.hasPassword(password, passwordLayout)){
progressBar.setVisibility(View.INVISIBLE);
return;
}
startSignIn(email.getText().toString(), password.getText().toString());
}
#OnClick(R.id.SignUpButton)
public void signUpScreen(){
Intent signup = new Intent(this, SignUpActivity.class);
startActivity(signup);
finish();
}
#OnTextChanged(value = R.id.LoginEmailText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
public void emailChanged(CharSequence s){
if(!(s.length() < 1)){
emailLayout.setError(null);
}
}
#OnTextChanged(value = R.id.LoginPasswordText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
public void passwordChanged(CharSequence s){
if(!(s.length() < 1)){
passwordLayout.setError(null);
}
}
private void startSignIn(String email, String password){
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(task -> {
try {
if (task.isSuccessful()) {
updateUI();
}
else {
String error = task.getException().getMessage();
if (error.contains("There is no user record corresponding to this identifier. The user may have been deleted.") ||
error.contains("The password is invalid or the user does not have a password."))
{
Utils.ErrorSweetDialog(LoginActivity.this, "Login Failed", "Incorrect email or pasword. Please try again.",
"OK");
}
else if (error.contains("A network error (such as timeout, interrupted connection or unreachable host) has occurred.")){
Utils.ErrorSweetDialog(LoginActivity.this, "No Internet Connection",
"Please check your internet connection and try again.", "OK");
}
else
{
Utils.ErrorSweetDialog(LoginActivity.this, "Login Failed", error, "OK");
}
}
progressBar.setVisibility(View.INVISIBLE);
}
catch (Exception e){
Utils.ErrorSweetDialog(LoginActivity.this, "Oops! Something went wrong.",
"Sorry for the inconvenience. Please try again later.", "OK");
}
});
}
#Override
protected void onStart() {
super.onStart();
//clearUserType();
//FirebaseUser user = firebaseAuth.getCurrentUser();
/*DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
}
}
else{
}
}
});*/
/*if(user != null){
//updateUI();
String uid = firebaseAuth.getCurrentUser().getUid();
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
if (userType.contains("parents")){
Log.e("contain parents", "yes");
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else{
}
}
}
else{
}
}
});
Intent intent = new Intent(this, ParentActivity.class);
startActivity(intent);
finish();
}
else{
Log.e("Login", "hi");
}*/
}
private void updateUI(){
Intent intent = new Intent(this, PickRoleActivity.class);
startActivity(intent);
finish();
}
private void clearUserType(){
FirebaseUser user = firebaseAuth.getCurrentUser();
//Log.e("urrent user", user.toString());
if(user != null){
progressBar.setVisibility(View.VISIBLE);
Log.e("user null: ", "no");
//updateUI();
String uid = firebaseAuth.getCurrentUser().getUid();
Log.e("UID: ",uid);
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
String childStatus = document.getString("child");
Log.e("LoginActivity",userType);
if (userType.contains("parents")){
Log.e("contain parents", "yes");
progressBar.setVisibility(View.INVISIBLE);
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else if (childStatus.contains("TRUE")){
progressBar.setVisibility(View.INVISIBLE);
}
}
}
else{
Log.e("task unsuccessful:", " yes");
}
}
});
}
else{
Log.e("NULL: ", "No Such User.");
}
}
}
User account data in firestore
I assume you are enabling creation of multiple accounts with the same email address, which means the parent and the child have different passwords. With that, I suggest you take a look at Custom Claims. It basically give an account a 'tag' that you can access client side. Please notice that this will require you to write some Cloud Functions when creating accounts
EDIT: It's seem that you need a SharedPreferences. Here are the docs : developer.android.com/training/data-storage/shared-preferences . This way you can store a key like isParent:true in a SharedPreferences, and read its value everytime the app is started instead of saving it to Firestore.
You can check them at onCreate for Login Activity or if you have Splash Activity, you can check there.
DocumentReference docRef = db.collection("UserInfo").document(uid); //ZJkUy7J5UzTok7ioADAYqk77Opp1
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
String userType = document.getString("userType");
Log.e("LoginActivity",userType);
if (userType.equal("parents")){
Log.e("contain parents", "yes");
Intent intent = new Intent(getApplicationContext(), ParentActivity.class);
startActivity(intent);
finish();
}
else if (userType.equal("child")) {
//Here you missed, when child login
}
}
}
}
});
In Local unit test, does VM allow to hit online through ParseUser, and Signup?
If you want to user Signup the user, you can use the code below:
ParseUser user = new ParseUser();
// Set the user's username and password, which can be obtained by a forms
user.setUsername(<Insert Username Here>);
user.setPassword(<Insert User Password Here>);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
alertDisplayer("Sucessful Sign Up!","Welcome" + <Insert Username Here> + "!");
} else {
ParseUser.logOut();
Toast.makeText(SignUpActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
If you need more information, at Back4App site have Docs about it and a template too :)
I'm trying to put data and sign in a user on ParseUser database, but I get the exception "invalid session token". I'm not sure about the user.put("fullname", fullname);.
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email, fullname, username, password;
email = emailEditText.getText().toString();
fullname = nameEditText.getText().toString();
username = usernaEditText.getText().toString();
password = passEditText.getText().toString();
if (!(email.isEmpty() || fullname.isEmpty() || username.isEmpty() || password.isEmpty())){
ParseUser user = new ParseUser();
user.put("fullname", fullname);
user.setEmail(email);
user.setUsername(username);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null){
Toast.makeText(SignUpActivity.this, "Sign up successful", Toast.LENGTH_SHORT).show();
}else {
if(e.getCode() == 202){
emailEditText.setText("");
nameEditText.setText("");
usernaEditText.setText("");
passEditText.setText("");
}
Toast.makeText(SignUpActivity.this, "Sign up failed "+ e.toString(), Toast.LENGTH_LONG).show();
}
}
});
This is the exception that the Toast shows
I've got this, just you have to log out with the current user, just put the code before ParseUser user = new ParseUser();
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.logOut();
I'm trying to make a signUp activity with a profile picture, but i get an error stating: Unable to encode an unsaved parse file. I have the same code in another Class and it doesn't have any problems.
I think that the problem could be using ParseUser instead of ParseObject. Please help me, here's my code.
public class SignUpActivityStep3 extends ActionBarActivity {
public static final String YOUR_APPLICATION_ID = "kuN8ihs88AYhRR1jIWT9psCGUXxSOveJPqVVsBnq";
public static final String YOUR_CLIENT_KEY = "vC4eA9CqulpgkxJ7sTPtoPSANkMxFeiFlYXwODYK";
byte[] Image;
ParseFile photo = null;
String User, Pass, Email, Description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signupstep3);
Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);
EditText Desc = (EditText) findViewById(R.id.txtDesc);
Button Finish = (Button) findViewById(R.id.btnFinish);
Intent intent = getIntent();
User = intent.getStringExtra("User");
Pass = intent.getStringExtra("Pass");
Email = intent.getStringExtra("Email");
Image = intent.getByteArrayExtra("Image");
photo = new ParseFile("userpicture.png", Image);
photo.saveInBackground();
savetoParse();
}
private void savetoParse() {
ParseUser user = new ParseUser();
user.setUsername(User.toString());
user.setPassword(Pass.toString());
user.put("Profile", photo);
user.setEmail(Email.toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getApplicationContext(),
"Saving user failed." + e.getMessage(), Toast.LENGTH_SHORT).show();
if (e.getCode() == 202) {
Toast.makeText(
getApplicationContext(),
"Username already taken. \n Please choose another username.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "User Saved",
Toast.LENGTH_SHORT).show();
/*Do some things here if you want to.*/
}
}
});
}
}
You need to wait for the Parse file to finish saving before attempting to sign up the user. You need to do something like this:
photo = new ParseFile("userpicture.png", Image);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// If successful add file to user and signUpInBackground
if(null == e)
savetoParse();
}
});
I was having this same issue but then I figured that for the image to be saved we need to login first, so either login with a user and password using ParseUser.LogInBackGround method or use Parse.enableLocalDatastore(this); to enable automatic user creation and logging in.
I have an android app in which user can change his/her password my problem is how i can verify old password of user using parse i have 3 edit text "old password, new password and confirm new password".
I search on parse.com but can't find any solution parse do not fetch data using get password.
i am doing this
String get_confrimpass=currentuser.getpassword();
if(get_confrimpass.replaceAll("\\s", "").equals(current_pass_check))
{ }
You can try logging them in using there current username and the password that they have given to you. If the loggin is successful the old password is correct. I.e
ParseUser.logInInBackground(ParseUser.getCurrentUser().getUsername(), currentPassword, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The password is correct
} else {
// The password was incorrect
}
}
});
In the example above the 'currentPassword' variable is the text that you would retreive from the 'Old Password' EditText
final ParseUser currentUser = ParseUser.getCurrentUser();
final String userName = ParseUser.getCurrentUser().getUsername();
ParseUser.logInInBackground(userName, oldPass, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (user != null) {
if (et.length() < 6)
Toast(getActivity(), "Password is short, Min char 6", Toast.LENGTH_LONG).show();
else {
currentUser.setPassword(newPass);
currentUser.saveInBackground();
ParseUser.logOut();
ParseUser.logInInBackground(userName, newPass, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
Toast(getActivity(), "Password change", Toast.LENGTH_LONG).show();
} else
Toast(getActivity(), "Network Error", Toast.LENGTH_LONG).show();
}
});
}
} else {
new CustomToast(getActivity(), "Old Password is incorrect", Toast.LENGTH_LONG);
}
}
});