follow the following step
1. Create a Facebook Test account
At first we have to create a new Facebook account. This account is known as test account. This account use in our android application. Do not use real Facebook account for development purpose.
When logged into Facebook, goto the Facebook Become Test Account page to convert your newly created account into a Facebook test account. Again, do not execute these steps on your “real” user account.
After confirming that you want to convert your account into a test account, you should see the following message : Your Account saurabh Sharma is now a Test Account.
2. Getting Application ID from Facebook
The application we want to integrate Facebook need an application ID from Facebook Developer Authentication . For more information visit on following link Facebook Developers Authentication
Creating an application cannot be done on the Facebook test account, so you’ll need to have a proper Facebook account in order to create the application. Using your “real” Facebook account, goto the Facebook Create Applicationpage and create your application.
Give it a name, and complete the registration. You should land on a page which have following information:-
App Id
*******
API Key
********
App Secret
********
Contact Email
***@****
Support Email
**@*****
3. Start Coding For Android Application
Everything is setup on the Facebook , now it’s time to start coding our Android application.
we can use the Facebook Android SDK located at Github : https://github.com/facebook/facebook-android-sdk
The Facebook Android SDK is licensed under the Apache License and is completely open source. Download it and import it in your Eclipse workSpcace.
Now create a new Android project named it "AndroidFacebook" and on MainActivity.class and activity_main.xml did following code.
1. MainActinity.class
In this class we will do two things : Authentication and Posting(Sharing). Before You post any thing on Facebook, We need Authentication, i.e User have to login on his Facebook Account and allow the permission for posting and accessing some basic information. Here is the codes of MainAvtivity here named as FacebookActivity:----
public class FacebookActivity extends Activity {//Global Variable;private static int RESULT_LOAD_IMAGE = 1;String picturePath ;Boolean selectedimage = false;EditText puttext;//Facebook Upload Variable startedprivate Button Upload_to_Facebook;private static final String APP_ID = "344638742254679";private static final String TOKEN = "access_token";private static final String EXPIRES = "expires_in";private static final String KEY = "facebook-credentials";private Facebook facebook;//Facebook Upload Variable Finished@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_facebook);puttext = (EditText)findViewById(R.id.editText1);findViewById(R.id.imageView1).setOnClickListener(new View.OnClickListener() { @Overridepublic void onClick(View v) {selectedimage = true;Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);startActivityForResult(i, RESULT_LOAD_IMAGE);}});facebook = new Facebook(APP_ID);restoreCredentials(facebook);findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(selectedimage){if(!puttext.getText().toString().equals("")){facebook.authorize(FacebookActivity.this,new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {@Overridepublic void onComplete(Bundle values) {postImage();Toast.makeText(getApplicationContext(), "Image Posted on Facebook.", Toast.LENGTH_SHORT).show();}@Overridepublic void onFacebookError(FacebookError error) {}@Overridepublic void onError(DialogError e) {}@Overridepublic void onCancel() {}});}else{Toast.makeText(getBaseContext(), "Please select text", Toast.LENGTH_SHORT).show();}}else{Toast.makeText(getBaseContext(), "Please select an image", Toast.LENGTH_SHORT).show();}}});}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {Uri selectedImage = data.getData();String[] filePathColumn = { MediaStore.Images.Media.DATA };Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);cursor.moveToFirst();int columnIndex = cursor.getColumnIndex(filePathColumn[0]);picturePath = cursor.getString(columnIndex);cursor.close();ImageView imageView = (ImageView) findViewById(R.id.imageView1);imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));}}public void postImage(){byte[] data = null;//String outPath = file.toString();String outPath = picturePath;Log.e("postWall", "postWall "+outPath);Bitmap bi = BitmapFactory.decodeFile(outPath);//Bitmap bi = BitmapFactory.decodeFile("/sdcard/img.jpg");//Bitmap bi = BitmapFactory.decodeResource(getResources(), R.drawable.icon);ByteArrayOutputStream baos = new ByteArrayOutputStream();bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);data = baos.toByteArray();Bundle params = new Bundle();params.putString(Facebook.TOKEN, facebook.getAccessToken());params.putString("method", "photos.upload");params.putByteArray("picture", data);// params.putString("message", puttext.getText().toString());// params.putString("description", "topic share");params.putString("caption", puttext.getText().toString());AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);}public class SampleUploadListener extends BaseKeyListener implements RequestListener {public void onComplete(final String response, final Object state) {try {// process the response here: (executed in background thread)Log.d("Facebook-Example", "Response: " + response.toString());JSONObject json = Util.parseJson(response);final String src = json.getString("src");Log.d("Facebook-Example", "URL: " + src.toString().trim());// then post the processed result back to the UI thread// if we do not do this, an runtime exception will be generated// e.g. "CalledFromWrongThreadException: Only the original// thread that created a view hierarchy can touch its views."} catch (JSONException e) {Log.w("Facebook-Example", "JSON Error in response");} catch (FacebookError e) {Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());}}public void onFacebookError(FacebookError e, Object state) {// TODO Auto-generated method stub}public Bitmap getInputType(Bitmap img) {// TODO Auto-generated method stubreturn img;}public int getInputType() {// TODO Auto-generated method stubreturn 0;}@Overridepublic void onIOException(IOException e, Object state) {// TODO Auto-generated method stub}@Overridepublic void onFileNotFoundException(FileNotFoundException e,Object state) {// TODO Auto-generated method stub}@Overridepublic void onMalformedURLException(MalformedURLException e,Object state) {// TODO Auto-generated method stub}}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();}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();}}
Here is the code for xml file
<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"tools:context=".FacebookActivity" ><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:text="@string/hello_world"android:textColor="#A52A2A"android:textStyle="bold"android:typeface="serif" /><ImageViewandroid:id="@+id/imageView1"android:layout_width="150dp"android:layout_height="150dp"android:layout_below="@+id/textView1"android:layout_centerHorizontal="true"android:layout_marginTop="40dp"android:src="@drawable/ic_launcher" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView1"android:layout_below="@+id/editText1"android:layout_marginTop="48dp"android:text="Share on Facebook" /><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/txt_id"android:layout_alignLeft="@+id/button1"android:layout_centerVertical="true"android:ems="10" ><requestFocus /></EditText><TextViewandroid:id="@+id/txt_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/editText1"android:layout_below="@+id/imageView1"android:text="Click on image to choose"android:textColor="#000"android:textStyle="bold" /></RelativeLayout>This is the final code for Facebook Integration in Android. By using this code you can share Image and text on facebook wall.ThanksHappy Coding!!!
can u send the source code for above Facebook integration in android to my mail
ReplyDeletenvraovenu@gmail.com