Search This Blog

Saturday, December 27, 2014

Parse.com anonymous and registered users (Android)

Introduction

When writing a mobile application you mostly always need a way to store the information outside of the application itself so the data is accessible to not only the application itself on a specific device, but on every device the application is installed on and perhaps even web applications. This means the application will need some sort of a backend service/API to communicate with. This usually also means the application will use some sort of account/user management.

There are several so-called mobile backend as a service platform which facilitate this. The word mobile is a bit misplaced I think because the clients of those platforms are not always mobile devices.  I therefor call those platforms Backend As a Service (BAAS). Parse.com is one of those platforms.

This post talks about the way you can manage users with Parse.com and specifically how to use anonymous users and convert between an anonymous and registered user.

Anonymous user

A lot of apps require the user to register (create a user account) or login with a Facebook or similar account. If this is a required process, chances are that a certain group of users will not use your app because of the required login. If your app functionality allows, a possible work-around for this is to provide the app with anonymous user login. By using an anonymous user, the user of your app can experience all or most of the functionality of the app without requiring a user account. If the user likes your app, he/she can then sign-up for a registered account. Ideally, all of the data gathered during anonymous access, should be transferred to the registered account. Fortunately, the above functionality is fairly easy to implement using the Parse.com platform.

Enabling anonymous access

To enable your Parse.com app for using anonymous access, you have to do the following:

1. Enable anonymous access in the Parse.com console. Go to Settings -> Authentication and enable "Allow anonymous access".

2. Add the following code in the onCreate method of your Android Application class:

@Override
    public void onCreate() {
        super.onCreate();
        Parse.initialize(this, "APPLICATION_ID", "CLIENT_KEY");
        ParseUser.enableAutomaticUser();
}

By enabling automatic user, the call to ParseUser.getCurrentUser() always returns a user and thus is never null. You can check if the user is an anonymous user or a registered one by using the following code:

ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser());

This can be useful to check if the sign-up button should be displayed or disabling some functionality which is only accessible to registered users.

Converting an anonymous user into a registered one

An anonymous user can be converted to a registered one. The data belonging to the anonymous user is also present on the registered one.

Before converting an anonymous user, there are some things to consider:

  1. The username can not be left blank. You must explicitly specify a username and password on the user which is to be converted into a registered one.
  2. It is adviced to save the anonymous user to the backend as soon as it is created. If this is not done and a call to saveInBackground is called on the registered user (after converting it from an anonymous one) a stack overflow is generated from the Android parse SDK. See also the following question on Stack-overflow (created by me): http://stackoverflow.com/questions/27595057/converting-an-anonymous-user-to-a-regular-user-and-saving
To save the user immediately after it is created, modify the Application code so that it looks like this:
@Override
    public void onCreate() {
        super.onCreate();
        Parse.initialize(this, "APPLICATION_ID", "CLIENT_KEY");
        ParseUser.enableAutomaticUser();
        ParseUser.getCurrentUser.saveInBackground();
}

The anonymous user can now be converted into a registered one with the following code:

findViewById(R.id.createUser).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                final String accountUsername = username.getText().toString();
                final String accountPassword = password.getText().toString();
                final ParseUser user = ParseUser.getCurrentUser();
                user.setUsername(accountUsername);
                user.setPassword(accountPassword);
                user.signUpInBackground(new SignUpCallback() {
                    @Override
                    public void done(final ParseException e) {
                        if (e != null) {
                            Toast.makeText(MainActivity.this, "Signup Fail", Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "Signup fail", e);
                        } else {
                            Toast.makeText(MainActivity.this, "Signup success", Toast.LENGTH_SHORT).show();
                            final ParseUser user = ParseUser.getCurrentUser();
                            user.put("phone_no", "31612345678");
                            user.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(final ParseException e) {
                                    if (e != null) {
                                        Toast.makeText(MainActivity.this, "Save data Fail", Toast.LENGTH_SHORT).show();
                                        Log.e(TAG, "Signup fail", e);
                                    } else {
                                        Toast.makeText(MainActivity.this, "Save data success", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        })

Please note that the data associated with the user in the saveInBackground call (after sign-up is successful) could also be associated immediately to the user before the signUp call. This saves an extra network call. The call to saveInBackground is pure for demonstration purposes.

Conclusion

This post showed the benefits of an anonymous user of a mobile app and how the anonymous user can be used with the Parse.com platform. It also showed code examples of how an anonymous user is converted into a registered one and the potential problems and solutions with it.

Saturday, February 8, 2014

IntelliJ: the power of structural search and replace

Sometimes you run into a situation where you want to refactor some code but cannot use the regular refactorings. For example, take the following code:

jQuery("body").on("change", "#fontSelector", "change", function () {
    var selectedFont = jQuery("#fontSelector").val();
    layoutDesigner.selectFont(selectedFont);
});

I wanted to replace the above code with the following:

jQuery("#fontSelector").off("change");
jQuery("#fontSelector").on("change", function () {
    var selectedFont = jQuery("#fontSelector").val();
    layoutDesigner.selectFont(selectedFont);
});

Sure, I could rewrite this manually. But this takes a long time with dozens of such event handling constructs, all with different selectors, events and functions. Structural search and replace to the rescue.

But instead of writing how you could do this with structural search and replace, I recorded a little screencast which demonstrates the concept. The video can be found here: https://www.youtube.com/watch?v=Jb-YNgDClKg

Tuesday, January 28, 2014

Android: location based services

Introduction

Developing applications for mobile devices gives us a lot more opportunities for context based information than a traditional web application. One of the inputs for context sensitive information is the users current location. This post describes several ways an Android application can obtain the users current location.

Location API's

In previous versions of the Android SDK you had to manually implement a location service which abstracts away the underlying location providers (GPS or cellular based). This was not ideal since as a developer of an application, you probably are not concerned about the implementation details of obtaining a users location.

Fortunately Google's Location API's provide a much better way for working with location data. The Location API's provide the following functionality:
  • Fused location provider which abstracts away the underlying location providers.
  • Geofencing. Lets your application setup geographic boundaries around specific locations and then receive notifications when the user enters or leaves those areas.
  • Activity recognition. Is the user walking or in a car.

Check for Google play services

Working with the Location API's require the presence of the Google Play Services application on the device. It is good practice to test for the presence of Google play services before using the API. This can be done with the following code:

protected boolean testPlayServices() {
        int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
            // google play services is missing!!!!
            /*
             * Returns status code indicating whether there was an error.
             * Can be one of following in ConnectionResult: SUCCESS, SERVICE_MISSING,
             * SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, SERVICE_INVALID.
             */
            GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, getActivity(), 1122).show();
            return false;
        }
        return true;
    }
Code listing 1

Code listing 1 shows how to check for the presence of Google play services. If the Google play services are not present a dialog is displayed giving the user the opportunity to download and install the Google play services application. This method returns false if the services are not found and can be placed around any code requiring Play services.

Obtaining the users location

The primary class for using the Location API's is the LocationClient. The first thing to do is instantiating the LocationClient and passing the required listeners. See the following code which is usually called from the onCreate from within an activity or onActivityCreated if the LocationClient is instantiated within a fragment.

locationClient = new LocationClient(getActivity(), this, this);

The parameters are:

  1. The Context
  2. ConnectionCallbacks. Defines the onConnected() and onDisconnected() methods.
  3. OnConnectionFailedListener. Defines the onConnectionFailed() method.
When the LocationClient is instantiated, the next thing to do is calling the connect() method of the LocationClient. This is typically done in the onResume method. In the inPause method the disconnect() method is called of the LocationClient. This ensures the LocationClient is only active when the activity is running. Should you need constant tracking of the users location when the app is in the background, it is better to create a background service for this.

When the connect() method is successful, the onConnected() callback is called. In this method you can obtain the users last known location using the following method:

locationClient.getLasLocation();

Periodic location updates

Registering for periodic location updates involves slightly more work. The first thing to do is creating a new LocationRequest object. This object specifies the quality of service for receiving location updates. The following code demonstrates this:

private static LocationRequest createLocationRequest() {
        final LocationRequest locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // The rate at which the application actively requests location updates.
        locationRequest.setInterval(60 * MILLISECONDS_IN_SECOND);
        // The fastest rate at which the application receives location updates, for example when another
        // application has requested a location update, this application also receives that event.
        locationRequest.setFastestInterval(10 * MILLISECONDS_IN_SECOND);
        return locationRequest;
    }

After the LocationRequest is created and the connect() method of the LocationClient is successful, the onConnected method is called. In this method the LocationClient is instructed to send periodic location updates to the application using the following code:

locationClient.requestLocationUpdates(locationRequest, this);

The parameters are:

  • locationRequest. Specifies the quality of services of the location updates.
  • LocationListener. Defines several callback methods including the onLocationChanged which is called when a new location is available.
Required dependencies

To use the Google play services in your application you have to define the correct dependencies in the build.gradle. There are two versions of the API: one for Android 2.3. and higher and one for Android 2.2.

Use the SDK manager to install the required packages. For Android 2.3 these are:

  • Google play services
  • Google repository
For Android 2.2 these are:
  • Google play services for Froyo
  • Google repository

So if your applications targets Android 2.2 you must use the Google play services for Froyo library. In your build.gradle specify the following dependency:

For Android 2.3:

dependencies {
    compile 'com.google.android.gms:play-services:4.0.30'
}

For Android 2.2:

dependencies {
    compile 'com.google.android.gms:play-services:3.2.65'
}

Testing with mock locations

To test with mock locations you have to do the following:


  1. Enable mock locations in the developer options.
  2. Download the sample LocationProvider example app: http://developer.android.com/training/location/location-testing.html
  3. Modify the LocationUtils class with an array of locations you want to test with.
  4. Install the LocationProvider sample app on your device.
  5. Start the LocationProvider sample app.
  6. Start the application you want to test the location functionality for.

A handy website to get the latitude and longitude of an address for testing purposes is: http://www.itouchmap.com/latlong.html

Conclusion

Working with location data in your mobile application can add a new dimension to the user experience. This article explains the steps needed to use the Google Location API's for obtaining the users current location.