Category Archives: Android Facebook

Tutoriale Android 05


Share on Facebook & E-Mail an Image from drawable folder :

First Create a Main Class called whatever you want.
I named it just Share.class

package www.wildalbsoft.com;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Share extends Activity {

Button Share;
EditText text;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.facebook_share);

		Share = (Button) findViewById(R.id.share_facebook);
		

		Share.setOnClickListener(new View.OnClickListener() {

		
			
				// TODO Auto-generated method stub
				public void onClick(View v) {
					
					final CharSequence[] items = { "facebook", "email" };

					AlertDialog.Builder builder = new AlertDialog.Builder(
							Share.this);

					builder.setTitle("Share");

					builder.setItems(items, new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int item) {
							// sharePos=mPager.getCurrentItem();
							if (item == 0) {

								Intent share = new Intent(Share.this,
										ShareFacebook_Image.class);
								share.putExtra("image", R.drawable.bleach);
								startActivity(share);

							}

							if (item == 1) {

								Intent shareIntent = new Intent(
								android.content.Intent.ACTION_SEND);
								shareIntent.setType("image/jpeg");
								shareIntent.putExtra(
										android.content.Intent.EXTRA_SUBJECT,
										"WildAlbSoft Tutorial Share!");
								shareIntent
										.putExtra(
												android.content.Intent.EXTRA_TEXT,
												"This is a test image! ");

									shareIntent.putExtra(
											Intent.EXTRA_STREAM,
											Uri.parse("android.resource://www.wildalbsoft.com/"
													+ R.drawable.bleach));
							
								startActivity(Intent.createChooser(shareIntent,
										"Share:"));

							}

						}

					});
					AlertDialog alert = builder.create();

					alert.show();

				}

		});
		
		

	}
}

after that another class called ShareFacebook_Image.class

package www.wildalbsoft.com;

import java.io.ByteArrayOutputStream;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

public class ShareFacebook_Image extends Activity {

	private static final String APP_ID = "YOUR APP ID CREATED FROM ANDROID DEVELOPER PANEL";

	private static final String[] PERMISSIONS = new String[] { "publish_stream" };

	private static final String TOKEN = "access_token";
	private static final String EXPIRES = "expires_in";
	private static final String KEY = "facebook-credentials";

	private Facebook facebook;
	private String messageToPost;

	Bundle extras;
	int image;

	public boolean saveCredentials(Facebook facebook) {
		// Editor editor = getApplicationContext().getSharedPreferences(KEY,
		// Context.MODE_PRIVATE).edit();
		// editor.putString(TOKEN, facebook.getAccessToken());
		// editor.putLong(EXPIRES, facebook.getAccessExpires());
		// return editor.commit();

		SharedPreferences settings = getSharedPreferences(KEY,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("silentMode", true);

		// Don't forget to commit your edits!!!
		return editor.commit();

	}

	public boolean restoreCredentials(Facebook facebook) {
		SharedPreferences sharedPreferences = getApplicationContext()
				.getSharedPreferences(KEY, Context.MODE_PRIVATE);
		facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
		facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
		return facebook.isSessionValid();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		facebook = new Facebook(APP_ID);
		restoreCredentials(facebook);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// setContentView(R.layout.facebook_dialog);

		String facebookMessage = getIntent().getStringExtra("facebookMessage");
		if (facebookMessage == null) {
			facebookMessage = "Test wall post";
		}
		messageToPost = facebookMessage;

		extras = getIntent().getExtras();
		// String text = extras.getString("text");
		image = extras.getInt("image");
		messageToPost = "";
		System.out.println("message to post:" + messageToPost);

		if (!facebook.isSessionValid()) {
			loginAndPostToWall();
		} else {
			postToWall(messageToPost);
		}

	}

	/*
	 * public void doNotShare(View button){ finish(); } public void share(View
	 * button){ if (! facebook.isSessionValid()) { loginAndPostToWall(); } else
	 * { postToWall(messageToPost); } }
	 */

	public void loginAndPostToWall() {
		
		//to force share on facebook from your app and not from facebook app you must set permissions to -1  🙂
		facebook.authorize(this, PERMISSIONS, -1, new LoginDialogListener());
	}

	public void postToWall(String message) {

		byte[] data = null;

		Bitmap bi = BitmapFactory.decodeResource(getResources(), image);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		data = baos.toByteArray();

		Bundle parameters = new Bundle();

		parameters
				.putString(
						"name",
						"Image uploaded from android WildAlbSoft Tutorial!");
		// parameters.putString("href", url);
		// parameters.putString("title", "Tramite iCalciatori Panini");
		// parameters.putString("description","Scarica anche tu da Google Play l'applicazione gratuita Pulcino Pio \n per il tuo smartphone Android!");
		// parameters.putString("caption", "TRAMITEiCalciatori Panini");
		// parameters.putString("link", "http://www.google.com");
		// parameters.putString("type", "jpeg");
		// parameters.putByteArray("source", data);
		// parameters.putString("method", "photos.upload");

		parameters.putByteArray("picture", data);

		try {
			facebook.request("me");
			String response = facebook.request("me/photos", parameters, "POST");
			Log.d("Tests", "got response: " + response);
			if (response == null || response.equals("")
					|| response.equals("false")) {
				showToast("Blank response.");
				finish();
			} else {
				showToast("Messaggio inviato al tuo facebook!");

			}
			finish();
		} catch (Exception e) {
			showToast("Impossibile inviare!");
			e.printStackTrace();
			finish();
		}
	}

	class LoginDialogListener implements DialogListener {
		public void onComplete(Bundle values) {
			saveCredentials(facebook);
			if (messageToPost != null) {
				postToWall(messageToPost);
			}
		}

		public void onFacebookError(FacebookError error) {
			showToast("Autenticazione con Facebook fallito!");
			finish();
		}

		public void onError(DialogError error) {
			showToast("Autenticazione con Facebook fallito!");
			finish();
		}

		public void onCancel() {
			showToast("Autenticazione con Facebook annullato!");
			finish();
		}
	}

	private void showToast(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
				.show();
	}
}

and the xml facebook_share.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <RelativeLayout android:id="@+id/layout_siper"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:background="@color/DarkCyan">
        
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/teks_qender"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:textColor="@color/White"
            android:textStyle="bold"
            android:typeface="serif"
            android:textSize="15sp"
            android:text="@string/text_facebook"/>
    </RelativeLayout>
    <RelativeLayout 
        android:id="@+id/layout_qender"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/layout_siper"
        android:layout_above="@+id/layout_poshte"
        android:background="@color/DimGray">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="46dp"
            android:src="@drawable/facebook" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imageView1"
            android:inputType="text"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="34dp"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/share_facebook"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editText1"
            android:layout_centerHorizontal="true"
            android:text="@string/share" />

        </RelativeLayout>
<RelativeLayout 
    	android:id="@+id/layout_poshte"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@color/DarkCyan">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/teks_poshte"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:textColor="@color/White"
            android:textStyle="bold"
            android:typeface="serif"
            android:textSize="15sp"
            android:text="@string/teks"/>
	</RelativeLayout>
</RelativeLayout>

Also you must download facebook sdk and import to your project as library.
Last thing,do not forget to declare your classes to the Manifest file and to add the permission needet like internet..