android get facebook username and id - android

i have very strange situetion. I 'm working facebook sdk in android. i wrote login code and also can check username and user id.but this code does not working when divice hase facebook application(i uninstalled it and then worked perfect)
this is a my code
public void LoginFacebook() {
mFacebook.authorize(this, mPermissions, new LoginDialogListener());
}
private final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
SessionStore.save(mFacebook, getApplicationContext());
getProfileInformation();
}
public void onCancel() {
SessionEvents.onLoginError("Action Canceled");
}
#Override
public void onFacebookError(FacebookError error) {
SessionEvents.onLoginError(error.getMessage());
}
#Override
public void onError(DialogError error) {
SessionEvents.onLoginError(error.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#SuppressLint("SdCardPath")
public void getProfileInformation() {
mAsyncRunner.request("me", new BaseRequestListener() {
#SuppressLint("CommitPrefEdits")
#Override
public void onComplete(String response, Object state) {
final String json = response;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject profile = new JSONObject(json);
facebook_userid = profile.getString("id");
facebook_username = profile.getString("name");
facebook_username = facebook_username.replace(
"%20", " ");
editor.putString("fb_name", facebook_username);
editor.putString("fb_id", facebook_userid);
fb_name.setText(facebook_username);
getFacebookAvatar(facebook_userid);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#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) {
}
});
}
i have no idea what is a wrong.
if anyone knows solution please help me thanks

Enable Client Deep Linking,Single Sign On and in advance tab OAuth Login from devlopers.facebook.com

You Can Do Like This.
public static void getuserdata() throws JSONException {
String Facebook = readT("https://graph.facebook.com/me?access_token="+mFacebook.getAccessToken()+"&fields=id,username)".replace(" ","%20"));
try
{
JSONObject jsonobj = new JSONObject(Facebook);
fb_id = jsonobj.getString("id");
fb_username = fb_fname+" "+fb_lname;
Log.e("..fb_username..........", fb_username);
}
catch (JSONException e)
{
e.printStackTrace();
}
}

Related

Facebook sdk not working in tablet (Android) it work fine in phone

In my application i am using Facebook SDK for login in to application. It will work fine without any error in phone but if i am test my in tablet it authorised user and generate the access token also but not fetch the user data. i am follow this link for this code http://sunil-android.blogspot.in/2013/08/facebook-integration-with-android-app.html
i am sharing my imported code part
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
String access_token = obj_pref.get_access_token();
long expires = obj_pref.get_access_expires();
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream",
"user_birthday" }, 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
obj_pref.set_access_token(facebook.getAccessToken());
obj_pref.set_access_expires(facebook.getAccessExpires());
getProfileInformation();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
} else if (facebook.isSessionValid()) {
getProfileInformation();
}
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
obj_pref.set_user_id(profile.getString("email"));
runOnUiThread(new Runnable() {
#Override
public void run() {
new send_fb_data().execute();
// upload user data to my database server
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#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) {
}
});
can any body help me out for this issue even in tablet it will not give any error ...

how to clear the session and token of facebook id,so as to login again

im my application,i can login to facebook and get the data,but when i click on logout,and then click on login again,it toast the message already login,but i want after logout,on login it again ask the login id and password,as all login requires.in on destroy i tried to clear the session,but it shows an error null exception in onDestroy. please suggest somthing
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
String access_token;
long expires;
private static 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()){
Session.initializeStaticContext(MainActivity.this.getApplicationContext());
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);
access_token = mPrefs.getString("access_token", null);
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(MainActivity.this, "already login", Toast.LENGTH_LONG).show();}
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) {
}
});
}
#Deprecated
public void logoutFromFacebook() {
mAsyncRunner.logout(MainActivity.this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
login.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
getData.setVisibility(View.INVISIBLE);
}
});
}
}
#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) {
}
});
}
#Override protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// if(fb.isSessionValid()){
Session.getActiveSession().closeAndClearTokenInformation();
// }
}
}
It is not guaranteed that onDestroy() method will call always called on activity finish.
So better you put that code of session clear in onPause() method.
UPDATE:
Do One more thing
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("access_token", null);
editor.commit();
SharedPreferences.Editor editor2 = getPreferences(MODE_PRIVATE).edit();
editor2.putLong("access_expires", 0);
editor2.commit();
Add this lines in your facebookLogout() method.
Because In your code I found that you are not checking for the session you checking this two variables to identify whether the user is login or not.
You can't rely to onDestroy to be called just after quiting your activity (finish()). it's usually the case but ondestroy can be called after a considerable delay.
you can call your cleaning code in onPause and you can enhance it like following:
#Override protected void onDestroy() {
super.onDestroy();
Session session = Session.getActiveSession();
if (session != null){
session.closeAndClearTokenInformation();
}
}
it is not known when onDestroy is going to call. it only invoke onStop and then move your activity to back. It is happen because if user again start this application , it will not have to load activity in ram again.because it a costly process to load activity in ram. so dont do any saving of data or any other work in onDestroy.move that work in onPause or in onStop.
read more here

Post text on facebook wall

I wish to post a text / link defined by me on my wall. The way I'm doing, okay opening the box wall and posting a text set time. I want to post a text as if it were a variable.
Eg String text = "Text to be posted"
and this text appear on my wall. Any idea?
public void postToWall() {
facebook.dialog(cxt, "feed",new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile
JSONObject profile = new JSONObject(json);
// nome usu�rio
final String name = profile.getString("name");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Comentário enviado com sucesso" + "Name: " + name,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
} }
#Override
public void onCancel() {
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
});
}

how to change the facebook profile picture using facebook android sdk?

my english is not so perfect but i want to learn, so i hope you can understand me. I wanna know how can i change the facebook profile pic using facebook android sdk. im able to upload pictures from my app to any album, including "Profile Pictures" (i use the next code:)
params=new Bundle();
params.putByteArray("photo", photo);
params.putString("caption", description);
mAsyncRunner.request(idAlbum+"/photos", params,"POST",new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {}
#Override
public void onIOException(IOException e,Object state) {}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state){}
#Override
public void onFacebookError(FacebookError e,Object state) {}
#Override
public void onComplete(String response, Object state) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_LONG).show();
}
});
}
}, null);
but i dont know how to set the uploaded image as the profile pic. maybe adding some code to this? I know that what i ask is posible using facebook sdk for php. also, i have seen an Apple app that do this too. Then, i think i can do it in android. somebody has information about what im looking for? thanks in advance.
Ok, I found the way to do that. and this is the code:
params=new Bundle();
try {
params.putByteArray("photo", photo);
} catch (IOException e) {
e.printStackTrace();
}
params.putString("caption", description);
mAsyncRunner.request(idAlbum+"/photos", params,"POST",
new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException
e, Object state) {}
#Override
public void onIOException(IOException e,Object state) {}
#Override
public void onFileNotFoundException(
FileNotFoundException e, Object state){}
#Override
public void onFacebookError(FacebookError e,Object state) {}
#Override
public void onComplete(final String response, Object state) {
mHandler.post(new Runnable() {
#Override
public void run() {
try {
JSONObject json=new JSONObject(response);
JSONObject obj=new JSONObject(
facebook.request("me"));
final String photoId=json.getString("id");
String userId=obj.getString("id");
String url="https://m.facebook.com/photo." +
"php?fbid="+photoId+"&id="+userId+
"&prof&__user="+userId;
Intent mIntent=new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(mIntent);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}, null);
Post the photo on a specific album, get the photoID with a JSONObject, and then redirect to a web page where the user can confirm to set the photo as his/her profile picture.

Facebook SSO , differentiating the login and wall post messages

I have made a sample for posting on Facebook using the basic Facebook library provided at developer.facebook.com and it works just fine with SSO,
btnPostOnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{
facebook.authorize(FBIntegrationSampleActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
if(values!=null && values.containsKey("access_token")){
postOnWall("NEW POST from" +count+"Android -Anuj");
Log.e("post on wall", "WALLPOST");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY POSTED MSG ON WALL", Toast.LENGTH_SHORT).show();
}else if(values!=null)
Log.e("LOGINE SUCCESS", "LOGIN SUCCESS");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY LOGGED IN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("onFBERROR", "ONFBERROR");
}
#Override
public void onError(DialogError e) {
Log.e("on DESI ERROR", "ON_ERROR");
}
#Override
public void onCancel() {
Log.e("onCANCEL", "ONCANCEL");
}
});
}
}
});
Which successfully posts on the Facebook wall, what i want is, I need to show the user that he has successfully signed in, and a message would be posted there after.
The Issue i face is the onComplete(Bundle values) method is called for both successful login and for successful post, how can i differentiate between both of them, is there a key in the Bundle values that can help to find the differnence?
Any suggestions are welcome.
Problem is that you are using for Authentication and Posting. No need to do like this :
For Authentication use
facebook.authorize(a, PERMISSIONS,-1,new LoginListener());
And for posting :
1) Without Dialog facebook.request(parameters)
2) With Dialog
facebook.dialog(this,"stream.publish",parameters,new TestUiServerListener());
public class TestUiServerListener implements DialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
new AsyncFacebookRunner(ZValues.authenticatedFacebook).request(postId,new TestPostRequestListener());
} else {
Post_Message_Title.this.runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
public class TestPostRequestListener implements RequestListener {
public void onComplete(final String response, final Object state) {
try {
JSONObject json = Util.parseJson(response);
String postId = json.getString("id");
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
} catch (Throwable e) {
}
}
public void onFacebookError(FacebookError e, final Object state) {
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
e.printStackTrace();
}
}
Just create a method successLoginShowDialog() and show whatever you want ,
If Post is success , In TestPostRequestListener below Thread will be called , so do all stuffs in this Thread :
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
to postOnWall() you can get its response:
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
fbObj.request("me");
String response = fbObj.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
// showToast("Blank response.");
Toast.makeText(context, "blank response", Toast.LENGTH_SHORT)
.show();
} else {
// showToast("Message posted to your facebook wall!");
Toast.makeText(context,
"Message posted to your facebook wall!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// showToast("Failed to post to wall!");
e.printStackTrace();
}
}

Categories

Resources