BackEndless - Test If User is Still Logged In

1.8k Views Asked by At

I'm using backendless.com for my backend. I have a login home screen:

enter image description here

The main Activity has a method from backendless.com that determines if the user is logged in. It returns a boolean statement and is placed in the onCreate method of the Activity:

AsyncCallback<Boolean> isValidLoginCallback = new AsyncCallback<Boolean>()
    {
        @Override
        public void handleResponse( Boolean response )
        {
            Toast.makeText(getApplicationContext(), "Logged In: " + response, Toast.LENGTH_LONG).show();
        }

        @Override
        public void handleFault( BackendlessFault fault )
        {
            Toast.makeText(getApplicationContext(), "An Issue Logging In", Toast.LENGTH_LONG).show();
        }

    };

When the app starts, the boolean value is false. The user then logs in and is taken to a 2nd Activity:

enter image description here Let's say that the user does not logout and simply closes the application. When they relaunch it, I need the application to begin with the 2nd Activity rather than the log in screen. In other words, is there some type of method that tests whether or not a user has remained logged in? I thought it would be the isValidLoginCallBack method above, however, when I close the application and relaunch it, the boolean value is once again false. I'm guessing this isn't the correct method to test that. I need something that persists. Does anyone have any suggestions? Thank you.

Here is the full code for the first Activity:

public class MainActivity extends AppCompatActivity {
private EditText nameInput, passwordInput, emailInput;
private Button register, login;
String name, password, email;
BackendlessUser user = new BackendlessUser();

@Override
protected void onCreate(Bundle savedInstanceState) {
    //NEED METHOD TO CHECK IF USER IS LOGGED IN.
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String appVersion = "v1";
    Backendless.initApp(this, "Blah", "F63A6CC8-4F6E-997D-FF88-1E6ADABFC200", appVersion);

    AsyncCallback<Boolean> isValidLoginCallback = new AsyncCallback<Boolean>()//THOUGHT THIS MIGHT BE IT BUT DOES NOT PERSIST
    {
        @Override
        public void handleResponse( Boolean response )
        {
            Toast.makeText(getApplicationContext(), "Logged In: " + response, Toast.LENGTH_LONG).show();
        }

        @Override
        public void handleFault( BackendlessFault fault )
        {
            Toast.makeText(getApplicationContext(), "An Issue Logging In", Toast.LENGTH_LONG).show();
        }

    };

    Backendless.UserService.isValidLogin( isValidLoginCallback );

    nameInput = (EditText)findViewById(R.id.nameInput);
    passwordInput = (EditText)findViewById(R.id.passwordInput);
    emailInput = (EditText)findViewById(R.id.emailInput);
    register = (Button) findViewById(R.id.buttonRegister);
    login = (Button) findViewById(R.id.buttonLogin);


    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            name = nameInput.getText().toString();
            password = passwordInput.getText().toString();
            email = emailInput.getText().toString();

            user.setEmail(email);
            user.setProperty("name", name);
            user.setPassword(password);

            Backendless.UserService.register(user, new AsyncCallback<BackendlessUser>() {
                public void handleResponse(BackendlessUser registeredUser) {
                    Toast.makeText(getApplicationContext(), "Registered!", Toast.LENGTH_LONG).show();
                }

                public void handleFault(BackendlessFault fault) {
                    Toast.makeText(getApplicationContext(), "Not Registered!" + fault, Toast.LENGTH_LONG).show();
                }
            });

        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            email = emailInput.getText().toString();
            password = passwordInput.getText().toString();

            Backendless.UserService.login(email, password, new AsyncCallback<BackendlessUser>() {
                public void handleResponse(BackendlessUser user) {
                    Toast.makeText(getApplicationContext(), "Logged In!", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(MainActivity.this, ActivityTwo.class);
                    startActivity(i);
                    finish();
                }

                public void handleFault(BackendlessFault fault) {
                    Toast.makeText(getApplicationContext(), "No Name", Toast.LENGTH_LONG).show();
                }
            });

        }
    });
}}
3

There are 3 best solutions below

1
On

You can use SharedPrefernces. Storing the data in shared preferences will be persistent even though user closes the application. Here is a tutorial.

You can also do it using the BackEndless SDK itself.

public void Backendless.UserService.login( String login, 
                                      String password, 
                                      boolean stayLoggedIn, 
                                      AsyncCallback<BackendlessUser> callback );

Here,stayLoggedIn requests to store the user's login information so the login form can be skipped next time the user launches the app. Use the following API to check if the application has user login information from previous runs:

// UserTokenStorageFactory is available in the com.backendless.persistence.local package

String userToken = UserTokenStorageFactory.instance().getStorage().get();

if( userToken != null && !userToken.equals( "" ) )
{  // user login is available, skip the login activity/login form }

I just copied the above code from official documentation here.

1
On

Backendless already uses SharedPreferences to store data between app restarts.

So you need to retrieve user after relaunch. First of all you need to set "stayLoggedIn" option while you login like this: Backendless.UserService.login("login", "password", <callback>, true);. Then Backendless stores your user ID and user token in shared prefs so it becomes accessible after app restart.

To check whether user token is valid just call Backendless.UserService.isValidLogin();

To get current user objectId use Backendless.UserService.loggedInUser(); Then you can grab user as ordinary object using Backendless.Data.findById(...).

I would strongly not recommend using Backendless.UserService.CurrentUser(). This method does not retrieve user from SharedPreferences so the result may be nullable. It does not check whether user is logger in so you may get inconsistent user session. Backendless is planning to improve it`s user management in future to move away from this method.

0
On

Just for the sake of completitude. Based on schaffe's answer, which is correct but methods are not completely accurate, I came up with a solution that is working for me.

 if (Backendless.UserService.isValidLogin()) {
      String userId = Backendless.UserService.loggedInUser();
      BackendlessUser user = Backendless.UserService.findById(userId);
      if (backendlessUser != null) {
           // Your user is logged in.
      }

There's a discussion on Backendless worth to read for further information.