How to connect to facebook from my application - android

I'm developing android app and i want user to connect Facebook when he open the app for the first time using Facebook SDK.
Then i want to post to the Facebook wall with specific message from my app. I try to use Facebook sdk with my app.I have made integration between mp app and Facebook sdk but i don't know how to do the task that log in to Facebook and post to the wall with the specific message.I search stackoverflow for this task and i found this code but i can't understand it
and it doesn't for me
public class MainActivity extends Activity {
Facebook facebookClient;
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebookClient=new Facebook("fb_App_id");
ImageButton facebookButton = (ImageButton) findViewById(R.id.button_FacebookShare);
facebookButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
if (facebookClient.isSessionValid()) {
postToWall();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookClient.authorizeCallback(requestCode, resultCode, data);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebookClient.setAccessToken(access_token);
}
if (expires != 0) {
facebookClient.setAccessExpires(expires);
}
if (!facebookClient.isSessionValid()) {
facebookClient.authorize(this, new String[] { "publish_stream" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebookClient.getAccessToken());
editor.putLong("access_expires", facebookClient.getAccessExpires());
editor.commit();
postToWall();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("name", "Battery Monitor");
parameters.putString("link", "https://play.google.com/store/apps/details?id=com.ck.batterymonitor");
parameters.putString("picture", "link to the picture");
parameters.putString("display", "page");
// parameters.putString("app_id", "228476323938322");
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}

You should refer to the following question on SO.
Facebook login and post
This code works. It will definitely solve your problem.

Try to use Android Simple Facebook (https://github.com/sromku/android-simple-facebook) - it's a layer to make the usage of Facebook SDK easier. According to the documentation, the login process would be something like this:
Initialize callback listener:
OnLoginListener onLoginListener = new OnLoginListener() {
#Override
public void onLogin() {
// change the state of the button or do whatever you want
Log.i(TAG, "Logged in");
}
#Override
public void onNotAcceptingPermissions(Permission.Type type) {
// user didn't accept READ or WRITE permission
Log.w(TAG, String.format("You didn't accept %s permissions", type.name()));
}
/*
* You can override other methods here:
* onThinking(), onFail(String reason), onException(Throwable throwable)
*/
};
Login:
mSimpleFacebook.login(onLoginListener);

Related

How to login using android-simple-facebook?

I need to get the basic user data, like Name, Email Address, Profile Picture, Birthdate etc.
I want to get this data from Facebook by offering users a login through Facebook in my android app instead of asking them to enter it manually.
I want to use android-simple-facebook https://github.com/sromku/android-simple-facebook for this purpose.
Can please someone give me a step by step instructions as to how to do it. The readme at their github account is too vague, to understand every step clearly.
I also had the same problem in doing this in Simple Facebook. So I just made a Helper class and use its method setLogin where I want to login.
public class FacebookHelper {
public OnLoginListener onLoginListener = null;
Button btnFacebook;
ProgressDialog mProgressDialog;
Context mContext;
public FacebookHelper(Context mContext) {
this.mContext = mContext;
}
public void setLogin() {
// Login listener
onLoginListener = new OnLoginListener() {
#Override
public void onThinking() {
// TODO Auto-generated method stub
}
#Override
public void onException(Throwable throwable) {
// TODO Auto-generated method stub
Toast.makeText(mContext, throwable + "", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onFail(String reason) {
Toast.makeText(mContext, reason + "", Toast.LENGTH_SHORT)
.show();
// TODO Auto-generated method stub
}
#Override
public void onLogin() {
// TODO Auto-generated method stub
publishPhoto();
}
#Override
public void onNotAcceptingPermissions(Type type) {
// TODO Auto-generated method stub
Toast.makeText(mContext, type + "", Toast.LENGTH_SHORT).show();
}
};
}
public void publishPhoto() {
// set privacy
Privacy privacy = new Privacy.Builder().setPrivacySettings(
PrivacySettings.ALL_FRIENDS).build();
Feed photo = new Feed.Builder()
.setName("Name")
.setDescription("Description")
.setPicture(
"http://www.bcre.com/images/laguna_beach_california_2592.jpg")
.setPrivacy(privacy).build();
SimpleFacebook.getInstance().publish(photo, true,
new OnPublishListener() {
#Override
public void onException(Throwable throwable) {
mProgressDialog.dismiss();
Toast.makeText(mContext, throwable.getMessage(),
Toast.LENGTH_LONG).show();
}
#Override
public void onFail(String reason) {
// mProgressDialog.dismiss();
Toast.makeText(mContext, reason, Toast.LENGTH_LONG)
.show();
}
#Override
public void onThinking() {
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle("Please Wait");
mProgressDialog.setMessage("UpLoading.....");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
public void onComplete(String response) {
// mProgressDialog.dismiss();
// Toast.makeText(mOCParksContext, response,
// Toast.LENGTH_LONG).show();
}
});
}
}
and then to call its methods just do this on your click. and initiating the objects in some override methods
mFacebookHelper.setLogin();
mSimpleFacebook.login(mFacebookHelper.onLoginListener);
#Override
protected void onResume() {
super.onResume();
mSimpleFacebook = SimpleFacebook.getInstance(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}

Opening Facebook login Dialog on Button Click

Hi Everyone I am intergrating facebook login to my app. I have searched a lot and I am able to login I have used this link: https://developers.facebook.com/docs/mobile/android/build/#register
All I want to do is that When I click on a Button then facebook dialog must appear intead of just opening the activity (HomeActivity) following is my code.
public class HomeActivity extends Activity {
Facebook facebook = new Facebook("114987225319269");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button more = (Button) findViewById(R.id.button1);
more.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
facebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
}
Use this code
Button more = (Button) findViewById(R.id.button1);
more.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (! facebook.isSessionValid()) {
facebook.authorize(HomeActivity.this, PERMISSIONS, new LoginDialogListener());
});
}
this is the login dialog listener
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
getAlbumsData task = new getAlbumsData();
task.execute();
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
In your Manifest
<activity
android:theme="#android:style/Theme.Translucent"
android:name=".HomeActivity "
>
This will change your activity theme into Dialog theme. Hope this helps...
This is all what you need:
public class BaseActivity extends Activity
{
public AsyncFacebookRunner mAsyncRunner;
public Facebook facebook;
public SharedPreferences mPrefs;
public static String appId = "123344";
SharedPreferences.Editor editor;
private void initialize()
{
facebook = new Facebook(appId);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void verifyLogin()
{
mPrefs = getPreferences(MODE_PRIVATE);
String accessToken = mPrefs.getString("access_token", null);
facebook.setAccessToken(accessToken);
long expires = mPrefs.getLong("access_expires", 0);
if (accessToken != null)
{
facebook.setAccessToken(accessToken);
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
facebook.authorize(this, new String[] {
"email", "publish_stream", "create_event"
}, new DialogListener()
{
#Override
public void onCancel()
{
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values)
{
// Function to handle complete event
// Edit Preferences and update facebook acess_token
editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error)
{
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror)
{
// Function to handle Facebook errors
}
});
}
}
}

Facebook api not working in my emulator?

I have implemented login with facebook in my project.
The code is below:
public class login extends Activity{
ImageView fbtn;
private SharedPreferences mPrefs;
static Facebook facebook = new Facebook("271089732997803");
String access_token;
long expires;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yf_login1);
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
fbtn = (ImageView)findViewById(R.id.fbtn);
fbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(access_token != null) {
facebook.setAccessToken(access_token);
Log.v("access_token", access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
Log.i("expires", ""+expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(login.this,new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
else{
startActivity(new Intent(login.this,ChooseTeam.class));
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
Now my question is when i click on the the fb button it will load the progress bar and after 30-40 second it returns the same page.
The most important thing is when i run the same project in my another pc it will run perfectly, opens the dialog of login for the facebook and got the value in my preferences. But in my case i cannot even get the preferences made in my data.
What will be the problem in my emulator?? I am using eclipse galilio and sdk20.
I got the solution actually my antivirus is blocked the internet for the emulator. So i have uninstalled the antivirus and run the app and it works.
Thank you all for helping me out.
Try this....
and use this Permission for Share in Facebook..
private String[] mPermissions={"publish_stream"};
mFb.authorize(SettingActivity.this, mPermissions,new com.fbintegration.Facebook.DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
SessionStore.save(mFb, getApplicationContext());
}
public void onCancel()
{
// TODO Auto-generated method stub
}
});
and this is Facebook Connector Class....
public class FacebookConnector
{
private Facebook facebook = null;
private Context context;
private String[] permissions;
private Handler mHandler;
private Activity activity;
//private SessionListener mSessionListener = new SessionListener();;
public FacebookConnector(String appId,Activity activity,Context context,String[] permissions)
{
this.facebook = new Facebook(appId);
SessionStore.restore(facebook, context);
this.context=context;
this.permissions=permissions;
this.mHandler = new Handler();
this.activity=activity;
}
public void login()
{
if (!facebook.isSessionValid())
{
facebook.authorize(this.activity, this.permissions,new LoginDialogListener());
}
}
/*public void logout()
{
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}*/
public void postMessageOnWall(String msg)
{
if (facebook.isSessionValid())
{
Bundle parameters = new Bundle();
parameters.putString("message", msg);
try
{
//JSONObject response=Util.parseJson(facebook.request("me/feed", parameters,"POST"));
String response = facebook.request("me/feed", parameters,"POST");
System.out.println(response);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
}
}
private final class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
SessionEvents.onLoginSuccess();
}
public void onFacebookError(FacebookError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onError(DialogError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onCancel()
{
SessionEvents.onLoginError("Action Canceled");
}
}
private class SessionListener implements AuthListener, LogoutListener
{
public void onAuthSucceed()
{
SessionStore.save(facebook, context);
}
public void onAuthFail(String error) {
}
public void onLogoutBegin() {
}
public void onLogoutFinish() {
SessionStore.clear(context);
}
}
public Facebook getFacebook()
{
return this.facebook;
}
}

Calling new activity after facebook login | Android

I have 2 activities in my android application. On the first one, I ask the user to login with facebook. after the user logs in, i collect the user data such as email, name and call a new activity passing these parameters to it. below is my facebook authorize method:
public void loginFB(final View v)
{
facebook.authorize(this, new String[] { "email", "read_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
this.getlogininfo(v);
}
private void getlogininfo(View v) {
// TODO Auto-generated method stub
logininfo(v);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
Below is my logininfo() method:
public void logininfo(final View v){
mAsyncRunner.request("me", new RequestListener(){
#Override
public void onComplete(String response, Object state) {
try{
Log.d("Profile", response.toString());
JSONObject json = Util.parseJson(response);
final String fname1 = json.getString("first_name");
final String lname1 = json.getString("last_name");
final String email = json.getString("email");
Intent fbLogged = new Intent();
Bundle passData = new Bundle();
passData.putString("fname", fname1);
passData.putString("lname", lname1);
passData.putString("email", email);
fbLogged.putExtras(passData);
fbLogged.setClass(v.getContext(), RequestFb.class);
startActivity(fbLogged);
}
catch(JSONException e){
Log.w("This", "eror");
}
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
});
}
So, my new activity is starting on OnComplete() of getting the user data.
This works perfectly, but when the user clicks login, and logs in with facebook, the first activity page remains on the screen for a few seconds and then the next activity is called. there is a lag. How can I fix the lag? When the user clicks login and after the login is authorized, it should take the user to directly the second activity. Any suggestions?
Thanks!
It's simple, you are running the fb graph request in a new thread (using the AsyncRunner) but only when that request is completed you start the new activity and that's why you get that "lag".
You should run the graph request in the new activity instead of the first one, something like:
public void loginFB(final View v) {
facebook.authorize(this, new String[] { "email", "read_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
Intent fbLogged = new Intent(v.getContext(), RequestFb.class);
startActivity(fbLogged);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
public class RequestFb extend Activity {
protected void onCreate(Bundle savedInstanceState) {
Facebook facebook = new Facebook("YOUR_APP_ID");
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(facebook);
asyncRunner.request("me", new RequestListener(){
try {
final JSONObject json = Util.parseJson(response);
final String fname1 = json.getString("first_name");
final String lname1 = json.getString("last_name");
final String email = json.getString("email");
runOnUiThread(new Runnable() {
public void run() {
// use the data
}
});
}
catch(JSONException e) {
Log.w("This", "eror");
}
});
}
}

How can I post link on facebook from android app using FB API?

I look all the internet and couldn't find how do I post link with a specific picture on facebook wall using fb sdk\api.
I know that this is part of the code that I need to use:
Facebook facebookClient = new Facebook("fb_App_id");
Bundle parameters = new Bundle();
parameters.putString("message", "Test Photo");
parameters.putString("link", "https://www.google.com");
parameters.putString("picture", "link to some pictrue");
facebookClient.dialog(MainActivity.this, "stream.publish", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
When I try to use this code I get "Source not found" error.
I think that I'm missing the connect\verification step...
How can I make it work?
Another thing: In case I use FB SDK in my personal app that I share on Google Play and this app is FREE but has Ads on it, Is it legal to use FB SDK in my app?
Finally I found how to do it.
You need to declare this two:
Facebook facebookClient;
SharedPreferences mPrefs;
In the onCreate function I initialize facebookClient with the facebook AppID.
The class that lunches the facebook share must be Activity
There are three functions that I added to the activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookClient.authorizeCallback(requestCode, resultCode, data);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebookClient.setAccessToken(access_token);
}
if (expires != 0) {
facebookClient.setAccessExpires(expires);
}
if (!facebookClient.isSessionValid()) {
facebookClient.authorize(this, new String[] { "publish_stream" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebookClient.getAccessToken());
editor.putLong("access_expires", facebookClient.getAccessExpires());
editor.commit();
postToWall();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("name", "Battery Monitor");
parameters.putString("link", "https://play.google.com/store/apps/details?id=com.ck.batterymonitor");
parameters.putString("picture", "link to the picture");
parameters.putString("display", "page");
// parameters.putString("app_id", "228476323938322");
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
and at last:
ImageButton facebookButton = (ImageButton) findViewById(R.id.button_FacebookShare);
facebookButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
if (facebookClient.isSessionValid()) {
postToWall();
}
}
});
It does an auto login to facebook and then displaies facebook share\post dialog.
The code was taken from this tutorial
I'm guessing that your problem is that you are using the stream.publish path which got deprecated:
Please note: We are in the process of deprecating the REST API, so if
you are building a new application you shouldn't use this function.
Instead use the Graph API and POST a Post object to the feed
connection of the User object
instead do this:
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
...
});

Categories

Resources