I am trying to implement Facebook SSO in my android app.It opens native Facebook app, after login process complete it shows "500: internal server error".What I am doing wrong?
Any suggestion will be highly appreciated .
Here is my code
public class FacebookUtil {
public static Facebook facebook = new Facebook(AppConstants.FACEBOOK_APP_ID);
String FILENAME = "AndroidSSO_data";
private static SharedPreferences mPrefs;
private static Context mContext;
private static boolean isSucess;
private static FacebookSucessListener mFacebookSucessListener;
public static final String FB_APP_SIGNATURE ="xxxxxxxxxxxxxxxxxxx";
public interface FacebookSucessListener {
public void onSucess(boolean isSucess);
}
public static void postToWall(){
facebook.dialog(mContext, "feed" , new DialogListener(){
public void onCancel() {
}
public void onComplete(Bundle arg0) {
}
public void onError(DialogError arg0) {
}
public void onFacebookError(FacebookError arg0) {
}});
}
/*
* Function to update status
* #param facebook acesstoken acess token
* #param String message to post
*/
public static void updateStatus(String accessToken, final String aMsgToShare){
try {
Bundle bundle = new Bundle();
bundle.putString("message", aMsgToShare);
bundle.putString(Facebook.TOKEN, accessToken);
String response = facebook.request("me/feed",bundle,"POST");
if(response.contains("Duplicate status message"))
Toast.makeText(mContext, "Duplicate message can not post", Toast.LENGTH_SHORT).show();
else if (response.contains("The user hasn't authorized the application to perform this action"))
Toast.makeText(mContext, "The user hasn't authorized the application to perform this action",Toast.LENGTH_SHORT).show();
else
Toast.makeText(mContext,"Posted Successfuly", Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e) {
Log.e("MALFORMED URL",""+e.getMessage());
} catch (IOException e) {
}
}
/*
* To logout from facebook
* #param Activity activity
* return response
*/
public static String logoutFacebook(Activity aActivity){
String resonse = "";
try {
String response = facebook.logout(aActivity.getApplicationContext());
} catch (Exception e) {
Log.e("LogoutException",""+e.getMessage());
}
return resonse;
}
/*
* TO start the facebook login process
* #param Activity activity
* #param SharedPreferences pref
* return true in case of sucess false otherwise
*/
public static void startLoginProcess(final Activity aActivity,final SharedPreferences mPrefs,FacebookSucessListener facebookSucessListener)
{
try{
mFacebookSucessListener = facebookSucessListener;
}catch(Exception e){}
/*
* Get existing access_token if any
*/
mContext=aActivity;
String access_token = mPrefs.getString("fb_access_token", null);
long expires = mPrefs.getLong("fb_expire_time", 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
boolean isSessionValid = facebook.isSessionValid();
if(!isSessionValid)
{
//Facebook.FORCE_DIALOG_AUTH
facebook.authorize( aActivity, AppConstants.permissions, 1, new DialogListener() {
public void onComplete(Bundle values) {
String token = values.getString(Facebook.TOKEN);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("fb_access_token", facebook.getAccessToken());
editor.putLong("fb_expire_time", facebook.getAccessExpires());
editor.putBoolean("is_fb_logged_in", true);
editor.commit();
mFacebookSucessListener.onSucess(true);
}
public void onFacebookError(FacebookError error) {
mFacebookSucessListener.onSucess(false);
Log.e("Facebook-onFacebookError", error.getMessage());
Toast.makeText(aActivity, "Error: "+ error.getMessage(), 600).show();
}
public void onError(DialogError e) {
mFacebookSucessListener.onSucess(false);
Log.e("Facebook-onError", e.getMessage());
Toast.makeText(aActivity, "Error: "+ e.getMessage(), 600).show();
}
public void onCancel() {
}
});
}
else {
mFacebookSucessListener.onSucess(true);
}
}
final class PostDialogListener implements DialogListener {
public void onComplete(Bundle values) {
}
public void onFacebookError(FacebookError error) {
Log.e("Facebook-onFacebookError", error.getMessage());
}
public void onError(DialogError error) {
Log.e("Facebook-onFacebookError", error.getMessage());
}
public void onCancel() {
}
}
}
Finally I solved my problem.The Has key, I was generating through CMD in window 7, was wrong.
So I generated this programmatically.
private void getHashKey()
{
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("your app package name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
//String something = new String(Base64.encode(md.digest(), 0));
String something = new String(Base64.encode(md.digest(),0));
Log.e("**** Hash Key", something);
}
}
catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
}
catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
}
catch (Exception e){
Log.e("exception", e.toString());
}
}
Related
I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// String access_token = mPrefs.getString("access_token", null);
//long expires = mPrefs.getLong("access_expires", 0);
// if (access_token != null) {
// facebook.setAccessToken(access_token);
// }
// if (expires != 0) {
// facebook.setAccessExpires(expires);
// }
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_actions" },
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
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.
in my application,i can loging through my facebook id.,it i enter another id,it didnot fetch data,as it do for my id.i can't understand what is the problem.when i enter another id,it showing loading,and after that onle blank facebook page is visible.
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
private AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
//updateButtonImage();
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
Log.e("name not found", e.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
}
}
#SuppressWarnings("deprecation")
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) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(getApplication(), "already login", Toast.LENGTH_LONG).show();
//logoutFromFacebook();
}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "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
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state) {
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I had the same problem. I fixed it like this.
Go to Facebook developers page
Apps --> "YourApp" --> Status and Review --> Enable ("Do you want to make this app and all its live features available to the general public?")
Like this
When you create app on Facebook. You might have testing and enabled sandbox mode as shown in image.you need to disable it.
Note: don't look at other settings.it is app for web,similarly you will have sandbox option for mobile app.
Your code is not updated for latest Facebook SDK 3.8, now Facebook provide Default class for Login, Share, Import Photo from Facebook and much more. Please follow this link
https://developers.facebook.com/docs/android/login-with-facebook/
I'm creating app that has share button on Facebook and I'm getting an error:
This Page Contains the following errors:
error on line 2 at column 182: Entityref: expecting ';'
Below is a rendering of the page up to the first error.
I don't get this error when I run the app on the Emulator. I'm only getting this kind of error when I run the app on the device.
What is the possible cause of this error?
Your help is highly appreciated. Thanks!
Code below is sample code for Facebook SDK:
public class FacebookShare extends Activity
{
private String APP_ID, APP_SECRET, Name, Link, Description, Picture;
private int fbTYPE;
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
private Activity ctx;
private Bitmap bitmap;
SharedPreferences mPrefs;
public FacebookShare(Activity ctx)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.ctx = ctx;
}
public void shareFB(int TypeOfSharing)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.fbTYPE = TypeOfSharing;
loginToFacebook();
}
public void loginToFacebook()
{
Log.v("debugging", "Entered Login to facebook");
String access_token = mPrefs.getString("access_token", "");
long expires = mPrefs.getLong("access_expires", 0);
if (!access_token.equals(""))
{
facebook.setAccessToken(access_token);
Log.v("Access Token", facebook.getAccessToken());
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
Log.v("debugging", "Session is Invalid");
facebook.authorize(ctx, new String[]{
"email","publish_stream"
}, facebook.FORCE_DIALOG_AUTH, new DialogListener()
{
public void onCancel()
{
// Function to handle cancel event
}
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", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
if (fbTYPE == 1)
{
postToWall();
}
else if (fbTYPE == 0)
{
postToWall(getBitmap());
}
}
public void onError(DialogError error)
{
Log.v("debugging", error.getMessage());
}
public void onFacebookError(FacebookError fberror)
{
Log.v("debugging", fberror.getMessage());
}
});
Log.v("debugging", "Passed from authorization");
}
else
{
if (fbTYPE == 1)
{
Log.v("debugging", "Entered Post to facebook");
postToWall();
}
else if (fbTYPE == 0)
{
Log.v("debugging", "Entered Post image to facebook");
postToWall(getBitmap());
}
}
}
public void clearCredentials()
{
try
{
facebook.logout(ctx);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void postToWall()
{
// post on user's wall.
Bundle params = new Bundle();
params.putString("description", getDescription());
params.putString("picture", getPicture());
params.putString("name", getName());
params.putString("link", getLink());
facebook.dialog(ctx, "feed", params, new DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
Toast.makeText(ctx, "Thanks for sharing JOLENPOP", Toast.LENGTH_SHORT).show();
}
public void onCancel()
{
// Login_Activity.asyncFBLogin fblogin = null;
// fblogin.execute();
}
});
}
public void postToWall(Bitmap bmImage)
{
Log.v("debugging", "entered postToWall(bitmap)");
byte[] data = null;
Bitmap bm = Bitmap.createBitmap(bmImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "post");
params.putString("message", getDescription());
params.putByteArray("image", data);
try
{
String response = facebook.request("me");
response = facebook.request("me/photos", params, "POST");
if (response == null || response.equals("") || response.equals("false"))
{
Log.v("response String", response);
return;
}
else if (response.toLowerCase().contains("error"))
{
Log.v("response String", response);
return;
}
}
catch (Exception e)
{
return;
}
Toast.makeText(ctx, "Your photo has been successfuly published!", Toast.LENGTH_LONG).show();
}
public void getProfileInformation()
{
mAsyncRunner.request("me", new RequestListener()
{
public void onComplete(String response, Object state)
{
Log.d("Profile", response);
String json = response;
try
{
JSONObject profile = new JSONObject(json);
// getting name of the user
String name = profile.getString("name");
// getting email of the user
String email = profile.getString("email");
runOnUiThread(new Runnable()
{
public void run()
{
// Toast.makeText(getApplicationContext(), "Name: " + name
// + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state)
{
}
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
public void onFacebookError(FacebookError e, Object state)
{
}
});
}
/**
* setters
* */
public void setFacebook(Facebook facebook)
{
this.facebook = facebook;
}
public void setAsyncRunner(AsyncFacebookRunner mAsyncRunner)
{
this.mAsyncRunner = mAsyncRunner;
}
public void setPrefs(SharedPreferences mPrefs)
{
this.mPrefs = mPrefs;
}
public void setName(String val)
{
this.Name = val;
}
public void setLink(String val)
{
this.Link = val;
}
public void setBitmap(Bitmap val)
{
this.bitmap = val;
}
public void setDescription(String val)
{
this.Description = val;
}
public void setPicture(String val)
{
this.Picture = val;
}
/**
* getters
* */
public String getAppID()
{
return this.APP_ID;
}
public String getName()
{
return this.Name;
}
public String getLink()
{
return this.Link;
}
public String getDescription()
{
return this.Description;
}
public String getPicture()
{
return this.Picture;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
Here how I used it:
fbShare = new FacebookShare(this);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
then;
Bitmap screenshot = this.glSurfaceView.mRenderer.screenCapture;
fbShare.setName("JOLENPOP");
fbShare.setDescription("I got a score of " + this.glSurfaceView.mRenderer.Score + " in JOLENPOP! Try to beat me!");
fbShare.setBitmap(screenshot);
fbShare.setPrefs(mPrefs);
fbShare.shareFB(0);
I'm having trouble setting up a simple facebook wall post to the user's wall.
I want a facebook dialog box to pop up on clicking a button with a thumbnail, description and title.
I have tried the following code but no dialog box pops up:
shareOnFacebookBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
/*
* Get existing access_token if any
*/
mPrefs ShopDetailActivity.this.getActivity().getPreferences(Context.MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
/*
* Only call authorize if the access_token has expired.
*/
if(!facebook.isSessionValid()) {
facebook.authorize(ShopDetailActivity.this.getActivity(),new String[] { "publish_stream" }, 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();
//facebook.dialog(ShopDetailActivity.this.getActivity(), "feed", new SampleDialogListener());
Bundle parameters = new Bundle();
parameters.putString("message", "message");// the message to post to the wall
facebook.dialog(context, "feed", parameters, this);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
}
});
The authorize window opens and after clicking allow I'd expect the dialog box to pop up but it just returns to the app.
What am I doing wrong?
facebook = new Facebook("your facebook id");
mAsyncRunner = new AsyncFacebookRunner(facebook);
facebook.authorize(this, new String[]
{ "publish_stream", "offline_access" }, -1,
new DialogListener()
{
public void onComplete(Bundle values)
{
Log.e("tag", "Values returned by Bundle ====> " + values.toString());
fbImageSubmit();
}
public void onFacebookError(FacebookError error)
{
}
public void onError(DialogError e)
{
}
public void onCancel()
{
}
});
//add method into your class
private void fbImageSubmit()
{
if (fb != null)
{
if (fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", your image url);
b.putString("caption", title);
b
.putString(
"description",
"test");
b.putString("name", "Hi Friends, I am using the your app name app for Android!");
b.putString("link", "https://market.android.com/details?id="+this.getApplication().getPackageName().toString());
try
{
String strRet = "";
strRet = fb.request("/me/feed", b, "POST");
JSONObject json;
try
{
json = Util.parseJson(strRet);
if (!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook", "Error: " + strRet);
}
} catch (FacebookError e)
{
Log.e("Facebook", "Error: " + e.getMessage());
}
} catch (Exception e)
{
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}
I want ask how can I redirect into someone's profile after successfully logging into Facebook?
Example : If successly logged in and authorized, it will direct into this page :
http://www.facebook.com/torasanshochiku.
I used this tutorial to connect Facebook
this is my FacebookConnectionActivity :
public abstract class FBConnectionActivity extends Activity {
public static final String TAG = "FACEBOOK";
private Facebook mFacebook;
public static final String APP_ID = "271496479563642";
private AsyncFacebookRunner mAsyncRunner;
private static final String[] PERMS = new String[] { "read_stream" };
private SharedPreferences sharedPrefs;
private Context mContext;
private TextView username;
private ProgressBar pb;
public void setConnection() {
mContext = this;
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
public void getID(TextView txtUserName, ProgressBar progbar) {
username = txtUserName;
pb = progbar;
if (isSession()) {
Log.d(TAG, "sessionValid");
mAsyncRunner.request("me", new IDRequestListener());
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
}
public boolean isSession() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String access_token = sharedPrefs.getString("access_token", "x");
Long expires = sharedPrefs.getLong("access_expires", -1);
Log.d(TAG, access_token);
if (access_token != null && expires != -1) {
mFacebook.setAccessToken(access_token);
mFacebook.setAccessExpires(expires);
}
return mFacebook.isSessionValid();
}
private class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
Log.d(TAG, "LoginONComplete");
String token = mFacebook.getAccessToken();
long token_expires = mFacebook.getAccessExpires();
Log.d(TAG, "AccessToken: " + token);
Log.d(TAG, "AccessExpires: " + token_expires);
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(mContext);
sharedPrefs.edit().putLong("access_expires", token_expires)
.commit();
sharedPrefs.edit().putString("access_token", token).commit();
mAsyncRunner.request("me", new IDRequestListener());
}
#Override
public void onFacebookError(FacebookError e) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
#Override
public void onError(DialogError e) {
Log.d(TAG, "Error: " + e.getMessage());
}
#Override
public void onCancel() {
Log.d(TAG, "OnCancel");
}
}
private class IDRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
try {
Log.d(TAG, "IDRequestONComplete");
Log.d(TAG, "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String id = json.getString("id");
final String name = json.getString("name");
FBConnectionActivity.this.runOnUiThread(new Runnable() {
public void run() {
username.setText("Welcome: " + name+"\n ID: "+id);
pb.setVisibility(ProgressBar.GONE);
}
});
} catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
} catch (FacebookError e) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
#Override
public void onIOException(IOException e, Object state) {
Log.d(TAG, "IOException: " + e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d(TAG, "FileNotFoundException: " + e.getMessage());
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d(TAG, "MalformedURLException: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
//#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
}
What you can do to redirect a user to someone's profile is use the generic profile page link.
It looks something like this -
//facebook.com/profile.php?id=USER_FBID
Where USER_FBID is the users Facebook ID. So all you need to do is have the users FBID and you can navigate directly to their profile with the link. Note that I'm using a protocol relative URL to keep the user in the same protocol when redirecting. If the user was browsing securely with HTTPS then they will be redirected to a secure link. If the user is not browsing securely then they will be directed to a normal HTTP link.