Android Facebook - Publish Photo to Timeline


This is an Android tutorial to show how to programmatically publish a photo to your Facebook timeline.

In this tutorial we make use of a small beautiful library called simple-fb.

Our Android Project Summary

Here's our project summary:

No. File Major Responsibility
1. build.gradle We add our simple-fb dependency here.
2. MyConfiguration.java To contain our Facebook API authentication details.
3. LogIn.java To log us in to our Facebook account.
4. PhotoPublisher.java To publish our photo an album in our account.
5. MainActivity.java Provide UI that allows us to achieve the above
6. activity_main.xml To define our MainActivity layout
7. content_main.xml Allow us add our widgets to our MainActivity
8. AndroidManifest.xml We need to add internet permission here.

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File --> New Project.

  2. Type the application name and choose the company name. New Project Dialog

  3. Choose minimum SDK. Choose minimum SDK

  4. Choose Basic activity. Choose Empty Activity

  5. Click Finish. Finish

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. MainActivity.java Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you've created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:


        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Advantage of Creating Basic Activity project

You can optionally choose empty activity over basic activity for this project.

However basic activity has the following advantages:

No. Advantage
1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
2. Provides us with appbar layout which implements material design appbar concepts.
3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
4. Decouples our custom content views and widgets from the templating features like toolbar.

Generated Project Structure

AndroidStudio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

2. Add Dependencies

Here's our dependencies in our app level build.gradle. Make sure you add the com.sromku:simple-fb dependency:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.sromku:simple-fb:4.1.1'

}

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

######### Advantages of Using XML over Java

No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It's easily maintanable as the user interface is decoupled from your Java logic.
3. It's easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project: ######## activity_main.xml

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed"

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application's top level decoration and is also specifies interactions and behavioros of all it's children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.

Here's our code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.facebookpublishphoto.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

######## content_main.xml This layout gets included in your activity_main.xml. You define your UI widgets right here.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.facebookpublishphoto.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

4. Java Classes

Here we go with our Java classes:

1. MyConfiguration.java

Here are the roles of this class:

No. Responsibility
1. Define an array of Facebook access Permissions. In this case we are interested in the Email permission as well as User photos permission.
2. Hold the umique app id for facebook. To work with facebook you need an app id. Please create a facebook app in your facebook account then bring the app id.There are plenty of tutorials of how to create a facebook app and obtain an app id online.
3. Build configuration via the SimpleFacebookConfiguration class and return the config object to be used when invoked.
package com.tutorials.hp.facebookpublishphoto.mFaceBook;

import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebookConfiguration;

public class MyConfiguration {

    Permission[] permissions=new Permission[]{Permission.EMAIL,Permission.USER_PHOTOS};
    static final String APP_ID="xxxxx";

    public SimpleFacebookConfiguration getMyConfigs()
    {
        SimpleFacebookConfiguration configs=new SimpleFacebookConfiguration.Builder()
                .setAppId(APP_ID)
                .setNamespace("facebookpublishphoto")
                .setPermissions(permissions)
                .build();

        return configs;
    }
}
2. Login.java

This class basically is used to login to Facebook. Here's how it works.

No. Responsibility
1. Accepts a Context object and a SimpleFacebook object on instantiation.
2. Logs the user in using the inbuilt login() method of SimpleFacebook class.
3. Listens to Facebook login callbacks.
4. When login is successful show a Toast message and publish a photo using the PhotoPublisher clas that we will see shortly.
5. When Cancelled show a toast message
6. Log exception and fail and possible reason for fail.
package com.tutorials.hp.facebookpublishphoto.mFaceBook;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.listeners.OnLoginListener;

import java.util.List;

public class LogIn {

    Context c;
    SimpleFacebook fb;

    public LogIn(Context c, SimpleFacebook fb) {
        this.c = c;
        this.fb = fb;
    }

    public void login()
    {
        fb.login(loginListener);
    }

    OnLoginListener loginListener=new OnLoginListener() {
        @Override
        public void onLogin(String accessToken, List<Permission> acceptedPermissions, List<Permission> declinedPermissions) {
            Toast.makeText(c,"Logged In",Toast.LENGTH_SHORT).show();
            //PUBLISH PHOTO
            new PhotoPublisher(c,fb).publishPhoto();
        }

        @Override
        public void onCancel() {
            Toast.makeText(c,"Cancelled ",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onException(Throwable throwable) {
            Log.e("Exception",throwable.getMessage());
        }

        @Override
        public void onFail(String reason) {
            Log.i("Fail", reason);
        }
    };
}
3. PhotoPublisher.java

This class publishes photo to an album in our Facebook account .

Here's it works.

No. Responsibility
1. Store an album id in a static data member. Go to your Facebook and get an id for one of your albums so that we will push a photo to that album.
2. Obtain a Context object and a SimpleFacebook object via the constructor and hold them in instance variables. The SimpleFacebook object will give us access to a publish() method which we'll use to publish the photo. The Context object will give us access to the getResources() method which we'll need when wanting to decode a drawable to a Bitmap.
3. Decode a Drawable to Bitmap. We get the photo as a drawable from your drawable folder. Please make sure you have a photo there!. Then we decode it from a drawable to a Bitmap using the static decodeResource() of the BitmapFactory class.
4. Once we have our Bitmap, we instantiate our Photo class.Then call obtain it's Builder to help us in building our Photo. We have it as a bitmap so we pass that bitmap to our setImage() method.That method like all builder methods returns an instance of teh Builder class so we proceed to fluently call the setName() passing in the text name of the photo.Then call the build() method to build it.
5. We now call the publish() method of our SimpleFacebook class, passing in the photo object, the album id and a publishlistener.
6. We'll now have our publishlistener to listen to various events during the photopublishing attempt. First we listen for completion method and display a Toast success message. We also listen to an exception event and log an error message . And Fail event and log reason.
package com.tutorials.hp.facebookpublishphoto.mFaceBook;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.entities.Photo;
import com.sromku.simple.fb.listeners.OnPublishListener;
import com.tutorials.hp.facebookpublishphoto.R;

public class PhotoPublisher {

    Context c;
    SimpleFacebook fb;
    static final String ALBUM_ID="962590287170645";

    public PhotoPublisher(Context c, SimpleFacebook fb) {
        this.c = c;
        this.fb = fb;
    }

    public void publishPhoto()
    {
        Bitmap bm= BitmapFactory.decodeResource(c.getResources(), R.drawable.hubble2);
        Photo photo=new Photo.Builder()
                .setImage(bm)
                .setName("Hubble Space Telescope Two")
                .build();

        fb.publish(photo,ALBUM_ID,publishListener);

    }

    OnPublishListener publishListener=new OnPublishListener() {
        @Override
        public void onComplete(String response) {
            super.onComplete(response);
            Toast.makeText(c, "Published Successfully", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onException(Throwable throwable) {
            super.onException(throwable);
            Log.e("Exception", throwable.getMessage());
        }

        @Override
        public void onFail(String reason) {
            super.onFail(reason);
            Log.i("Fail", reason);
        }
    };
}
4. MainActivity.java

This is our main activity.

Here's how it works with respect to its responsibilities:

No. Responsibility
1. Maintain a SimpleFacebook object as a data member
2. Listen to onCreate() callback.
3. Inflate the activity_main.xml inside the onCreate() Activity callback.
4. Reference a Toolbar and set it as an actionbar for our Activity.
5. Instatiate our MyConfiguration class and pass it into the static setConfiguration() method of our SimpleFacebook class.
.6. Reference our FloatingActionButton and listen to it's click events.
7. Log user in when the FloatingActionButton is clicked.
8. Listen to Activity's onResume() event, then reobtain SimpleFacebook instance. and assign it to our data member variable.
package com.tutorials.hp.facebookpublishphoto;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import com.sromku.simple.fb.SimpleFacebook;
import com.tutorials.hp.facebookpublishphoto.mFaceBook.LogIn;
import com.tutorials.hp.facebookpublishphoto.mFaceBook.MyConfiguration;

public class MainActivity extends AppCompatActivity {

   SimpleFacebook fb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

         SimpleFacebook.setConfiguration(new MyConfiguration().getMyConfigs());
        fb=SimpleFacebook.getInstance(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  new LogIn(MainActivity.this,fb).login();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        fb=SimpleFacebook.getInstance(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        fb.onActivityResult(requestCode, resultCode, data);
    }
}

5. AndroidManifest.xml

First we need to add permission for internet inside the manifest:

<manifest>
    ....
    <uses-permission android:name="android.permission.INTERNET"/>
    ....
</manifest>

Then add a Facebook activity and meta data inside the component:

<manifest>
<application>
...
    <activity android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:label="@string/app_name" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
...
</application>
</manifest>

And that's it.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post