Software Development

Building A Chat App With Codename One Part 3

In the previous section we went over the login with Google process, in this section we’ll go over the login with Facebook. At this time we’ll skip the “invite friends” option since that is blog post all on its own and we can just add that functionality to the completed application.

With Google we will use our email as the unique identifier but Facebook might not expose user names. However, Facebook does have a “get friends” API call that we can use, the downside of that is that it will only return our friends that have already joined the app so we won’t be able to contact anyone on an arbitrary basis.

Getting Started – Configuration

Getting started with Facebook is pretty similar to the Google process and you can learn about it here.

You need to go to https://developers.facebook.com/apps/ and signup to create an application:

chat-app-tutorial-facebook-login-2

You need to repeat the process for web, Android & iOS (web is used by the simulator):

chat-app-tutorial-facebook-login-3

For the first platform you need to enter the app name:

chat-app-tutorial-facebook-login-4

And provide some basic details:

chat-app-tutorial-facebook-login-5

For iOS we need the bundle ID which is the exact same thing we used in the Google+ login to identify the iOS app its effectively your package name:

chat-app-tutorial-facebook-login-6

You should end up with something that looks like this:

chat-app-tutorial-facebook-login-7

The Android process is pretty similar but in this case we need the activity name too.

Important: notice there is a mistake in the screenshot, the activity name should match the main class name followed by the word Stub (uppercase s). In this case it should be SocialChatStub.

chat-app-tutorial-facebook-login-8

Just like on Google+ we need to generate a hash to verify that the app is indeed ours to Facebook and we do this using the same keytool approach using the command line:

keytool -exportcert -alias (your_keystore_alias) -keystore (path_to_your_keystore) | openssl sha1 -binary | openssl base64

Lastly you need to publish the Facebook app by flipping the switch in the apps “Status & Review” page as such:

chat-app-tutorial-facebook-login-9

Project Configuration

We now need to set some important build hints in the project so it will work correctly. To set the build hints just right click the project select project properties and in the Codename One section pick the second tab. Add these entries into the table:

facebook.appId=...

The app ID will be visible in your Facebook app page in the top left position.

The Code

So now that all of that is in place we would want it to work with our app…​

Add the event handling for logging in with Facebook as such:

loginWithFacebook.addActionListener((e) -> {
    tokenPrefix = "facebook";
    Login fb = FacebookConnect.getInstance();
    fb.setClientId("739727009469185");
    fb.setRedirectURI("http://www.codenameone.com/");
    fb.setClientSecret("-------");
    doLogin(fb, new FacebookData());
});

Notice that the client ID, redirect, secret etc. are all relevant to the simulator login and won’t be used on Android/iOS where native Facebook login will kick into place.

Similarly to the Google+ implementation we’ll create a class to abstract the Facebook connection based on the interface we defined the last time around:

static class FacebookData implements UserData {
        String name;
        String id;

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getId() {
            return id;
        }

        @Override
        public String getImage() {
            return "http://graph.facebook.com/v2.4/" + id + "/picture";
        }

        @Override
        public void fetchData(String token, Runnable callback) {
            ConnectionRequest req = new ConnectionRequest() {
                @Override
                protected void readResponse(InputStream input) throws IOException {
                    JSONParser parser = new JSONParser();
                    Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
                    name = (String) parsed.get("name");
                    id = (String) parsed.get("id");
                }

                @Override
                protected void postResponse() {
                    callback.run();
                }
            };
            req.setPost(false);
            req.setUrl("https://graph.facebook.com/v2.4/me");
            req.addArgumentNoEncoding("access_token", token);
            NetworkManager.getInstance().addToQueue(req);
        }
}

This is really trivial code, we just connect to Facebooks Graph API and provide the token. From here on its just a matter of parsing the returned data which contains only two keys for the user name and the unique id which we can use later on when setting up a chat.

That’s it for Facebook login, next time we’ll get into accessing the contacts and showing the contacts form UI.

Other Posts In This Series

This is an ongoing series of posts including the following parts:

Reference: Building A Chat App With Codename One Part 3 from our JCG partner Shai Almog at the Codename One blog.

Shai Almog

Shai is the co-founder of Codename One, he has been programming professionally for over 20 years and developing in Java since 96. Shai worked for countless industry leaders including Sun Microsystems where he was a part of the original WTK (Wireless Toolkit) team & the co-creator of LWUIT. He worked with most major device operators/manufactures including Nokia, Samsung, Sony Ericson, Sprint, Vodafone, Verizon, NTT DoCoMo etc. Shai is a blogger and writer who often speaks at conventions. He is a Java One rockstar and top rated speaker for JavaZone, corporate conventions from Oracle, IBM and many others.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button