Android Share Images or Content To Facebook From Android Application Tutorial using Facebook SDK

This tutorial explains how to quick share images or content from Android Application to Facebook

Integrate Facebook to Android App

This tutorial helps to share content or images from your Android Application to Facebook. In the previous tutorial Android Facebook Integration and Login Tutorial, I explained how to integrate Android Application to Facebook and how to login through Facebook button.

Android Facebook Share Dialog

Setup ContentProvider

Don't Miss

Without using ContentProvider, we can not share any content on the Timeline. You also need to set up a ContentProvider in your AndroidManifest.xml where {APP_ID} is your app ID:

<provider android:authorities="com.facebook.app.FacebookContentProvider{APP_ID}"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="true"/>

Add publish_actions Permission

Add email and publish_actions permission, when user log into Application.

loginButton.setReadPermissions("email, publish_actions");

Add Layout

We have already created UserProfile Activity in the Previous Tutorial. Now, we add button to share content and image. We will share image to choose Phone Gallery, take instant picture. Add below code int the acitivity_user_profile.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    tools:context="in.studytitorial.androidfaceboklogin.UserProfile">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/profilePic"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profilePic"
        android:id="@+id/UserName"
        android:text=""/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/email"
        android:layout_below="@+id/UserName"
        android:text=""/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/email"
        android:layout_marginTop="20dp"
        android:text="Share Content"/>
    <Button
        android:id="@+id/imageShare"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:layout_below="@+id/button"
        android:layout_marginTop="20dp"
        android:background="@drawable/share_image" />

</RelativeLayout>
Android Facebook Share Layout

Share Content in Facebook

We need to initialize a Share dialog to share the content on the Facebook from Android Device.
The Share dialog open a popup with content, where you tag and post content. To show the ShareDialog for a link in your activity, create a ShareDialog instance in your onCreate method then show the ShareDialog. Use the following code in UserProfile.java

JSONObject response, profile_pic_data, profile_pic_url;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
ShareDialog shareDialog;
protected void onCreate(Bundle savedInstanceState) {

    Button button = (Button) findViewById(R.id.button);
    shareDialog = new ShareDialog(this);  // initialize facebook shareDialog.
    button.setOnClickListener(new View.OnClickListener() {
    @Override
   public void onClick(View v) {
   if (ShareDialog.canShow(ShareLinkContent.class)) {
         ShareLinkContent linkContent = new ShareLinkContent.Builder()
             .setContentTitle("Android Facebook Integration and Login Tutorial")
             .setImageUrl(Uri.parse("https://www.studytutorial.in/
                   wp-content/uploads/2017/02/FacebookLoginButton-min-300x136.png"))
             .setContentDescription(
                     "This tutorial explains how to integrate Facebook and Login
                     through Android Application")
             .setContentUrl(Uri.parse("https://www.studytutorial.in/
                         android-facebook-integration-and-login-tutorial"))
             .build();
                shareDialog.show(linkContent);  // Show facebook ShareDialog
       }
    }
});
Android Facebook Share Dialog

Handle the response

onActivityResult method handle the sharing content

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

Sharing Image on Facebook

To share images on Facebook, we will provide a dialog box in which an option to select image from the Gallery or instant take an image to share on Facebook. Initialize button in onCreate() method. Call selectImageToShareFacebook() to open dialog box onclick button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_profile);
    imageShare.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          selectImageToShareFacebook();
        }
    });
}

Create selectImageToShareFacebook()

In this method, we will create a dialog box in which option to select image.

private void selectImageToShareFacebook() {
        final CharSequence[] items = { "Take Photo", "Choose from Library",
                "Cancel" };
                AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
        builder.setTitle("Select profile Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_FILE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
Android Share dialog

Convert image in Bitmap format

After selection or capture of image, onActivityResult() method handle the response and send it onSelectFromGalleryResult() and onCaptureImageResult() method to convert image into bitmap format.

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

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
            else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }
 }

 private void onSelectFromGalleryResult(Intent data) {
        Uri selectedImageUri = data.getData();
        String[] projection = { MediaStore.MediaColumns.DATA };
        Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
                null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        cursor.moveToFirst();
        String selectedImagePath = cursor.getString(column_index);
        Bitmap thumbnail;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(selectedImagePath, options);
        final int REQUIRED_SIZE = 200;
        int scale = 1;
        while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                &amp;amp;&amp;amp; options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        thumbnail = BitmapFactory.decodeFile(selectedImagePath, options);
        ShareDialog(thumbnail);
}

private void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ShareDialog(thumbnail);
 }

Adding content into SharePhotoContent model

To share image, we will use SharePhotoContent model which provided by Facebook SDK. SharePhotoContent model support bitmap photo. So We have already converted image into bitmap format.

public void ShareDialog(Bitmap imagePath){
        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(imagePath)
                .setCaption("StudyTutorial")
                .build();
        SharePhotoContent content = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();
        shareDialog.show(content);
}
Android Share POST
Notification

10 COMMENTS

  1. i got the FileNotFoundException in onSelectFromGalleryResult(). Bitmap doesn’t get right path. i don’t understand what is the problem in the code

  2. […] Facebook provides shareDialog class to share images or content on facebook. You can read more details, check here […]

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com