Followers

Wednesday, July 11, 2012

Facebook Integration with Android App - PostToWall Dynamic message

Steps to Integrate Facebook in Android Application:
1. download facebook library from https://github.com/facebook/facebook-android-sdk/
2. create a new android project with existing source code and give the path of above downloaded "facebook" folder only.
3. create new project.
4. First Activity:



package com.taran.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class PostMsgActivity extends Activity {
Button btnShow;
EditText etText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("t","ONCreate....");
setContentView(R.layout.main);
}
protected void onStart() {
super.onStart();
Log.v("t","onStart....");
btnShow = (Button)findViewById(R.id.btnShow);
etText = (EditText)findViewById(R.id.etText);

btnShow.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = etText.getText().toString();
Intent intent = new Intent(PostMsgActivity.this,FBAppActivity.class);
intent.putExtra("facebookMessage", str);
startActivity(intent);

}
});

}

}

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="250dp"
    android:layout_height="125dp" >

    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="SHOW" />

    <EditText
        android:id="@+id/etText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:ems="10" />

</RelativeLayout>


Second Activity:

package com.taran.android;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

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

public class FBAppActivity extends Activity {
private static final String APP_ID = "434327979941439";
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;

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();
}

@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_sample);

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

public void doNotShare(View button) {
finish();
}

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

public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}

public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
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("Authentication with Facebook failed!");
finish();
}

public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}

public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}

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


}


Facebook_sample.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="250dp"
    android:layout_height="125dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:padding="5dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="5dp"
            android:text="Do you want to share this on Facebook?" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/FacebookShareButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_margin="2dp"
            android:onClick="share"
            android:padding="5dp"
            android:text="Yes" />

        <Button
            android:id="@+id/FacebookShareNotButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_margin="2dp"
            android:onClick="doNotShare"
            android:padding="5dp"
            android:text="No" />
    </LinearLayout>

</RelativeLayout>

AndroidManifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.taran.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".PostMsgActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".FBAppActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Dialog" >
        </activity>
    </application>

</manifest>

Any Confusions,Feel free to ask.








31 comments:

  1. Break your 3 normal main meals into 5 smaller portion sizes - morning,
    snack, lunch, snack, dinner. In fact, I always suggest to those overweight
    vegetarians to keep to a max of 4 pounds a week so you won't suffer loose skin post weight loss. Do not be tempted to lose weight as quickly as you can, because a crash diet will have you eating less than a thousand calories a day slowing down your metabolism.

    Here is my web page: http://www.5-10kgabnehmen.de

    ReplyDelete
  2. During the summer of 2008 I started using internet radio to
    reach an even wider audience. As business owners
    recognize the swaying power of using audio to communicate the
    value and quality of their products and services, online audio will come of age in a big way.

    Organizing employees, maintenance of radio station as well as layout
    and other details are very simple and therefore creating
    a radio station online is a lucrative deal for those who want their own stations.



    Here is my web-site ... online-radioportal.de

    ReplyDelete
  3. Una Musica Brutal, by Gotan Project: from Buddha Bar IV. As we ate, not only
    did our waitress check back with us to see if we required anything further, but the manager
    stopped by as well. Quicker to produce and available in lower costs,
    they often feature a lot of complex designs.



    Here is my web page :: click the up coming article

    ReplyDelete
  4. You have to give a tube radio at least 20 to 30 minutes just to warm up and then you decide
    what frequency you want to be on and load the plate
    and tune them up. Often, long term schedules with a bit of breathing room work best.

    These channels offer a variety of genres for the user.


    My web blog; www.rffst.org

    ReplyDelete
  5. Webcams can do a lot of things, such as video conferencing, virtual advertising, workplace or home surveillance, event broadcast, and many other functions.
    One of the first recommendations to be made about
    powered laptop coolers is to, in general, stay away from folding coolers unless space and convenience are of premium concern.

    This trackball is perfect for people who are short on space and have
    a small work area.

    Visit my web-site - http://www.brandisworld.com/

    ReplyDelete
  6. Let's think of words that sound dirty but really aren't.

    they simply need to learn that you will not be able to appease everyone of your player-base.
    It fizzles as the lights go out, and she says it's been great talking to you.

    My website - http://www.spielespielen24.de

    ReplyDelete
  7. It really is developed in this type of way that it
    makes the driver comfortable and in charge
    as if they are driving an actual car. I am one of
    those night owl gamers that plays in the evening, and don't like too much lighting around me. Click it and look inside for the folder regarding keyboards.

    My homepage - Email Console

    ReplyDelete
  8. You have to give a tube radio at least 20 to 30 minutes just to warm up
    and then you decide what frequency you want to be on and load the plate and tune them up.
    It was an entertaining radio program that played the music people wanted to hear combined with
    his groovy upbeat personality. These channels offer a
    variety of genres for the user.

    My page; radio booster for android

    ReplyDelete
  9. While these parks aren't the same, you might need to carefully analyze the price of them. Once you decide what kind of Oregon coast camping vacation you are looking for, finding an Oregon coast camping site is a piece of cake. Many of the most pleasant trips we've had were at
    camp sites that were relatively basic yet in the midst
    of beautiful countryside.

    Here is my web page :: http://ipstube.ips.k12.in.us/

    ReplyDelete
  10. With internet radio, you get pretty much what you want, when you want.
    Wi - Fi internet radio is a new handy device for all music lovers of this world,
    which is a gift of the technology to the entertainment world.
    Back in the day, people had little choice but
    to take what was given to them as their "lot in life.

    Feel free to surf to my webpage: click through the following post

    ReplyDelete
  11. During the summer of 2008 I started using internet radio to
    reach an even wider audience. If you are already experienced in
    internet radio hosting, the Blog - Talk - Radio Premium might be a
    hosting program you might want to pay for. This powerful and versatile solution is also available in three different versions,
    so you should have no trouble finding the perfect one for you.


    Here is my site; profileone.co.kr/xe/?document_srl=159&mid=product

    ReplyDelete
  12. If you are receiving a fatal exception error message or BSOD with error
    message while installing or playing Real - Arcade games, take note of the stop error code
    and then temporary disable avast or turn on Gaming or Silent mode
    in the Avast progr am. However, antivirus problems like Avast often conflict with
    Real - Arcade games due to the following error or virus detection:.
    4) As people showed up to vote KEEP, they were frequently branded "sockpuppets",
    banned, and their comments stricken from the discussion.

    my blog: Spiele spielen kostenlos

    ReplyDelete
  13. If with the classic version, you only get to play the same
    game over and over again, with Simon 2 game, you
    get to play more games with more challenges ad game highlights.
    All that energy is boxed in, amplified by the space. Most video game testers reported that their salary falls between $15,000 and $55, 000
    in a year.

    my blog myrtle beach real estate

    ReplyDelete
  14. This comment has been removed by a blog administrator.

    ReplyDelete
    Replies
    1. May I know why are you continously posting this unrelated material?

      Delete
  15. When tomorrow's bread is not assured from today's labor, with
    day to day grim experiences, one is inclined to go for criminal options.
    Though, none of this can be confirmed, it's been alleged that the police have a recording in which Gibson can be heard saying, "Fuck the Jews'the Jews are responsible for all the
    wars of the world, fuck the Jews. Blige, Trey Songz, and more, the 14-track
    album has hosted positive reactions from critics on its dual themes held together by Meek's knack for storytelling:.

    Also visit my web-site; http://www.mswebmedia.de/shitstorm-kaufen/jetzt-sthitstorm-kaufen.html

    ReplyDelete
  16. This comment has been removed by a blog administrator.

    ReplyDelete
  17. Whilst you could get a partner or close friend to
    give your shoulders, back or feet a good rub down, to truly feel long-term benefits you should enlist the services
    of a trained professional to give you regular massages.
    One of the key reasons for this effect is that these types of music utilize
    a tempo between 55 and 85 beats per minute. This was a live performance recorded
    by Dutch national television, 2 April 2011 (therefore it isn't fully cough free), by four pianists: Elisabeth Bergmann, Marcel Bergmann, Sandra van Veen, and Jeroen van Veen.

    Here is my site: Author's external home page.

    .. - gisoracle.cemagref.fr

    ReplyDelete
  18. Multiplayer versions is more exciting as in this, you'll be able to team up or even contend with other participants to defeat the enemies. Port forwarding lets you specify which ports the game needs to perform at it's
    best. Well, you can have that same chess engine on your
    Android mobile phone, courtesy of Droid - Fish.



    Visit my weblog :: cpmpac.org

    ReplyDelete
  19. This comment has been removed by a blog administrator.

    ReplyDelete
  20. This comment has been removed by a blog administrator.

    ReplyDelete
  21. In the four tournaments since his first of the season, he.
    A bowler who can consistently pick up his spares can easily hold
    a 180 average without getting any strikes. It is recommended
    that the golfers select those putters with which the golfers feel good and works well with their gaming pattern.



    My blog post :: kostenlos spielen

    ReplyDelete
  22. Una Musica Brutal, by Gotan Project: from Buddha Bar IV.
    Compassion also arises out of a sense of vulnerability and shared
    humanity'the realization that we are all connected to everyone and everything at all times, that we are not isolated or separate. I would recommend having a Mimosa out on the patio overlooking the waterway.

    Here is my homepage ... 2009년 실적발표 - 2009-11-30 redemption of the outstanding convertible bonds and withdrawal Of listing

    ReplyDelete
  23. This method of Fishing
    also has a by-catch of non-target species such as sharks,
    dolphins, turtles, and other non-target fish species.
    Here is some helpful information so you can select a good charter boat and avoid a few of the pitfalls.
    Yet sometimes a net is better to use because it usually doesn't harm the fish and will most likely be easier for you to prepare the fish for later.

    ReplyDelete
  24. Once you have done this, set the burn speed to 4x and click Burn and wait for
    it to complete. The only downside of it in a lot of people's eyes is the fact that there is no multiplayer content. If you want to be able to hit the ball further and harder, you should keep in mind to keep your grip on the bat loose, your swing should begin with your legs and hips, and finally, you must always follow your bat through.

    My blog :: http://anticoediquinzio.altervista.org/

    ReplyDelete
  25. Like any game, when we stay within the rules, we
    score, and when we play outside the rules there of course is a penalty.

    Age Level - A good factor to write about is the appropriate age level for
    the video game that you are reviewing. But what happens
    when a player runs out of race tokens.

    Also visit my web page :: http://wequietsleep.org/PorterFhp - altervista.org -

    ReplyDelete
  26. If you just want to do a few cakes for right now you may be able to borrow most of the items or get cheaper versions of each
    tool. If you prefer to use frozen strawberries, they work in this
    cake equally as well as the fresh. This birthday cake recipe will give you a 4-layer chocolate cake with whipped
    cream as a filling between the layers.

    Have a look at my homepage: cake affairs houston texas

    ReplyDelete
  27. Signing up for the particular Wilton Process Redecorating Principles Study course is good
    for those people thinking of getting a jump in cake adorning.
    The good part of it here is that the act of doing so
    does not require any kind of skill or competence. The TV crew
    will embark on the task of helping "sweet" businesses
    survive and prosper.

    Here is my webpage cake arts toledo ()

    ReplyDelete
  28. I cover my freshly sharpened hook with paste and coat the hair
    and bait in paste. Here is some helpful information so
    you can select a good charter boat and avoid a few of
    the pitfalls. When the water arrives at the inlet, most oxygen is dissolved
    because of the abrupt transformation of water movement.


    Feel free to visit my site - http://www.acps.org/new/html/modules.php?name=Your_Account&op=userinfo&username=MilfordSa

    ReplyDelete
  29. Try simple games and check how your internet connection is and then move on play more games.

    The only downside of it in a lot of people's eyes is the fact that there is no multiplayer content. The most unique thing about Ouya is that it is said to be "open" -- although what this means is up for interpretation.

    Feel free to visit my webpage: http://web2101258.hkhz5.badudns.cc/plus/guestbook.php

    ReplyDelete
  30. Ultimately, this ruined the entire story for me and it almost made me turn people away from the film.
    At the same time, in the same interview, Takaya Imamura stated that "the story ends here", which has
    thrown some fans for a loop. Kanye West – “Heartless” Mixed With Lady Gaga
    – “Lovegame”.

    My webpage ... Daft Punk Random Access Memories Flac Free Download

    ReplyDelete