Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Self-Destructing Message Android App Adding Users Using Parse.com Logging In

jenyufu
jenyufu
3,311 Points

How do I make the Username login field also accept logging via the email they signed up for?

I want to make it like most websites where you can sign in with either Username or email.

2 Answers

If I'm understanding you right, you wanted to allow the user to type in either their username or email in the edittext on the login screen and sign in to their account. I don't know if Parse.com provides any function doing that but I'm guessing no.

I would suggest you start by checking user's input in the username edittext field and see if it contains "@" symbol.

If it doesn't, simply proceed with normal login process.

If it does contain "@", you will know it's an email input. Set up a query for ParseUser looking for one with that email address and get the username so you can use it to do normal login. Of course if no user with that email is found, just throw out some toast or alert dialog telling user to try again.

And obviously it is necessary to make sure your users' usernames don't include "@" in the first place when they sign up.

Edit: I was thinking about something like this.

// checks if Username field contains "@", mUsername is the text extracted from username edittext.
if(mUsername.contains("@")){
    // if it does, what the user typed in the Username EditText should be an email address
    // set up query looking for any user with that email address
    ParseQuery<ParseUser> emailLoginQuery = ParseUser.getQuery();
    emailLoginQuery.whereEqualTo("email", mUsername);
    emailLoginQuery.findInBackground(new FindCallback<ParseUser>() {
        @Override
        public void done(List<ParseUser> list, ParseException e) {
            if(list.size() == 0){
                // if the result list size is 0, no user with entered email exists.
                // Set up an alert dialog or something
            }else{
                // otherwise there should be 1 user with that email, so we update the mUsername variable with his/her actual username 
                mUsername = list.get(0).getUsername();
                // use this updated mUsername to perform login process
                logIn();
            }
        }
    });
}else {
    // if mUsername doesn't inlude "@", perform normal login
    // logIn() would be a function containing the ParseUser.logInInBackground()... codes
    logIn();
}

As of making sure users don't sign up with username including "@", simple if(username.indexOf("@")) or contains("@") should be enough I suppose.

And I didn't even think about checking as username first, I just thought maybe prevent users from being able to create new account with "@" in their usernames .

jenyufu

jenyufu
jenyufu
3,311 Points

"And obviously it is necessary to make sure your users' usernames don't include "@" in the first place when they sign up."

So to avoid that, I can just check username first, and then check email if username doesn't work so it will allow for people with "@" in their username to login?

so something like:

if (username.indexOf("@"))

honestly, I'm still pretty confused and help would be much appreciated.

jenyufu
jenyufu
3,311 Points

oh and here is my code to LoginActivity right now

public class LoginActivity extends Activity {

    private EditText usernameView;
    private EditText passwordView;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        // Set up the login form.
        usernameView = (EditText) findViewById(R.id.username);
        passwordView = (EditText) findViewById(R.id.password);



        // Set up the submit button click handler
        findViewById(R.id.action_button).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Validate the log in data
                boolean validationError = false;
                StringBuilder validationErrorMessage =
                        new StringBuilder(getResources().getString(R.string.error_intro));
                if (isEmpty(usernameView)) {
                    validationError = true;
                    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
                }
                if (isEmpty(passwordView)) {
                    if (validationError) {
                        validationErrorMessage.append(getResources().getString(R.string.error_join));
                    }
                    validationError = true;
                    validationErrorMessage.append(getResources().getString(R.string.error_blank_password));
                }
                validationErrorMessage.append(getResources().getString(R.string.error_end));

                // If there is a validation error, display the error
                if (validationError) {
                    Toast.makeText(LoginActivity.this, validationErrorMessage.toString(), Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                // Set up a progress dialog
                final ProgressDialog dlg = new ProgressDialog(LoginActivity.this);
                dlg.setTitle("Please wait.");
                dlg.setMessage("Logging in.  Please wait.");
                dlg.show();

                // Call the Parse login method
                ParseUser.logInInBackground(usernameView.getText().toString(), passwordView.getText()
                        .toString(), new LogInCallback() {

                    @Override
                    public void done(ParseUser user, ParseException e) {
                        dlg.dismiss();
                        if (e != null) {
                            // Show the error message
                            Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        } else {
                            // Start an intent for the dispatch activity
                            Intent intent = new Intent(LoginActivity.this, DispatchActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }
                });
            }
        });
    }

    private boolean isEmpty(EditText etText) {
        if (etText.getText().toString().trim().length() > 0) {
            return false;
        } else {
            return true;
        }
    }
}
jenyufu
jenyufu
3,311 Points

It worked!!! thanks, I have been trying to solve this problem for days. Here is the code for anyone in the future to look at:

my LoginActivity is a bit different from the one in the tutorial because mine was built with ParseLogin. The main difference being I didn't immediately convert my usernameVariable with .getText().toString(); until way later.

package com.parse.mealspotting;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.RequestPasswordResetCallback;

import java.util.List;

/**
 * Created by Fu on 7/30/2015.
 */
public class LoginActivity extends Activity {

    private EditText usernameView;
    private EditText passwordView;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        // Set up the login form.
        usernameView = (EditText) findViewById(R.id.username);
        passwordView = (EditText) findViewById(R.id.password);



        // Set up the submit button click handler
        findViewById(R.id.action_button).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Validate the log in data
                boolean validationError = false;
                StringBuilder validationErrorMessage =
                        new StringBuilder(getResources().getString(R.string.error_intro));
                if (isEmpty(usernameView)) {
                    validationError = true;
                    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
                }
                if (isEmpty(passwordView)) {
                    if (validationError) {
                        validationErrorMessage.append(getResources().getString(R.string.error_join));
                    }
                    validationError = true;
                    validationErrorMessage.append(getResources().getString(R.string.error_blank_password));
                }
                validationErrorMessage.append(getResources().getString(R.string.error_end));

                // If there is a validation error, display the error
                if (validationError) {
                    Toast.makeText(LoginActivity.this, validationErrorMessage.toString(), Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                // Set up a progress dialog
                final ProgressDialog dlg = new ProgressDialog(LoginActivity.this);
                dlg.setTitle("Login-ing in...");
                dlg.setMessage("Patience, my young Padawan.");
                dlg.show();

                //I started the code here: (here is where I converted usernameVariable to a String, unlike most of the treehouse students who converted it early on in the code like this:  "String mUsername = usernameField.getText().toString();"
                String mUsername = usernameView.getText().toString();

                // checks if Username field contains "@", mUsername is the text extracted from username edittext.
                if(mUsername.contains("@")){
                    // if it does, what the user typed in the Username EditText should be an email address
                    // set up query looking for any user with that email address
                    ParseQuery<ParseUser> emailLoginQuery = ParseUser.getQuery();
                    emailLoginQuery.whereEqualTo("email", mUsername);
                    emailLoginQuery.findInBackground(new FindCallback<ParseUser>() {
                        @Override
                        public void done(List<ParseUser> list, ParseException e) {
                            if(list.size() == 0){
                                // if the result list size is 0, no user with entered email exists.
                                // Set up an alert dialog or something
                                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                            }else{
                                // otherwise there should be 1 user with that email, so we update the mUsername variable with his/her actual username
                                final String mUsername = list.get(0).getUsername();
                                // use this updated mUsername to perform login process
                                // Call the Parse login method need to refactor this[1]
                                ParseUser.logInInBackground(mUsername, passwordView.getText().toString(), new LogInCallback() {
                                    @Override
                                    public void done(ParseUser user, ParseException e) {
                                        dlg.dismiss();
                                        if (e != null) {
                                            // Show the error message
                                            Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                        } else {
                                            // Start an intent for the dispatch activity
                                            Intent intent = new Intent(LoginActivity.this, DispatchActivity.class);
                                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            startActivity(intent);
                                        }
                                    }
                                });
                            }
                        }
                    });
                }else {
                    // if mUsername doesn't inlude "@", perform normal login
                    // logIn() would be a function containing the ParseUser.logInInBackground()... codes
                    // Call the Parse login method need to refactor this[1]
                    ParseUser.logInInBackground(mUsername, passwordView.getText().toString(), new LogInCallback() {
                        @Override
                        public void done(ParseUser user, ParseException e) {
                            dlg.dismiss();
                            if (e != null) {
                                // Show the error message
                                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                            } else {
                                // Start an intent for the dispatch activity
                                Intent intent = new Intent(LoginActivity.this, DispatchActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        }
                    });
                }
            }
        });
    }

    private boolean isEmpty(EditText etText) {
        if (etText.getText().toString().trim().length() > 0) {
            return false;
        } else {
            return true;
        }
    }
}
```java
Douglas Counts
Douglas Counts
10,126 Points

To do that, simply send both fields even if one is an empty string. Then check which was submitted on the back end with an if-statement.