How to get Facebook user name in android app - android

I added Facebook login function to my application. it was successfully connect and logout from the application.
I want to print that login user name in my application.
Can anyone help meto find this?
I used This as example
This is my code.
fbLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
fb.authorize(MainActivity.this, new String[]{"email"}, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
updateButtonImage();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "onCancel", Toast.LENGTH_LONG).show();
}
});
}
}
});

you need to refer this link facebook sdk
and get information from user object.
Bundle params = new Bundle();
params.putString("fields", "name,first_name,last_name");
friendsRequest.setParameters(params);
// Get current logged in user information
Request meRequest = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
FacebookRequestError error = response.getError();
if (error != null) {
Log.e(FriendSmashApplication.TAG, error.toString());
handleError(error, true);
} else if (session == Session.getActiveSession()) {
// Set the currentFBUser attribute
((FriendSmashApplication)getApplication()).setCurrentFBUser(user);
}
}
});
or you can try this example.
http://www.androiddevelopersolution.com/2012/09/android-facebook-integration.html

I would follow this Facebook doc on how to fetch the user's data after he logged into your application.

Related

Using access token on graph api

I am trying to get JSON data from this url.
As you can see I need access token to get this.
So far I am able to login to facebook and get user access token
`fb.authorize(MainActivity.this, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnFbError", Toast.LENGTH_SHORT);
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnError", Toast.LENGTH_SHORT);
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "OnComplete", Toast.LENGTH_SHORT);
Editor editor=sp.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
try {
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(MainActivity.this, NewsFeed.class);
startActivity(i);
}`
How to use this access token to access the json data?
By using Facebook SDK you can manage authentication and token by the Session class. getAccessToken() method in session class is responsible to provide token.
Session session = Session.getActiveSession();
if (session != null && session.getState().isOpened()){
Log.i("sessionToken", session.getAccessToken());
Log.i("sessionTokenDueDate", session.getExpirationDate().toLocaleString());
}
By using this access token u can get user image as:
https://graph.facebook.com/me/picture?access_token=<your_access_token_here>

error in using android-facebook-sdk

I am just not able to figure out the problem in my code
I want to login with FaceBook for my app
I have followed a tutorial from a youtube video.
in the code , I am able to login using facebook, but I am not able to implement the logout functionality.
i tried doing it. (the code for logging out is also there but still its not working)
the code is as follows:
after i click on login button:
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.fb_button:
try{
//to check if already logged in.
//my code never enters the following block.
if(fb.isSessionValid()){
Toast.makeText(getBaseContext(), "loging out", Toast.LENGTH_LONG).show();
try {
fb.logout(getBaseContext());
// update_fb_buttonimage() is a function to change the image of button
//if logged in: it shows logout
// else it shows login.
//but somehow its not working
update_fb_buttonimage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//following is working fine.
// but every time i click n the button, it enters this bolok of code.
//which is not what i want. this is tobe executed only if user is not logged in
//even if user is logged in , program enters this code only.
// instead of this th above "if" block should be executed.
else{
Toast.makeText(getBaseContext(), "logging in", Toast.LENGTH_LONG).show();
fb.authorize(LoginPage.this,new DialogListener(){
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
update_fb_buttonimage();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "You can't login to the facebook", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "unIdentified Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "onCancel", Toast.LENGTH_LONG).show();
}} );
} }catch(Exception e){
System.out.print(e.toString());
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
break;
}
Where is my error?
just replace the MainActivity.this with yours and updateButtonImage()
if(fb.isSessionValid())
{
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button close session
}
else
{
fb.authorize(MainActivity.this,new String[] {"publish_stream"}, new DialogListener(){
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(MainActivity.this, "on Facebook error", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(MainActivity.this, "on error", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
updateButtonImage();
}
#Override
public void onCancel()
{
}
});
//login in to facebook
}

Android facebook sdk 3.0 logout not working?

I'm using facebook sdk 3.0 to login my application. login working fine. once i logout my application it's not happening.
my logout code:
Facebook mFb=new Facebook("xxxxxxxx");
mFb.logout(this);
give me some idea to do this.
I have been facing same problem finally i found this fix
public void logout()
{
Session session = Session.getActiveSession();
if (session != null) {
session.closeAndClearTokenInformation();
}
else
{
Session session2 = Session.openActiveSession((Activity)context, false, null);
if(session2 != null)
session2.closeAndClearTokenInformation();
}
Session.setActiveSession(null);
}
I do not know whats going inside but i guess we will have to create new session if it is not found and clear token information for it.
It worked for me. hope it will help.
Try this:
if( mFb.isSessionValid() ) {
mFb.logout(getApplicationContext());
SessionStore.clear(getApplicationContext());
}
Ans: Working fine
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, Exception exception){
// TODO Auto-generated method stub
if(session.isOpened()){
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if(user!=null){
try{
session.close();
session.closeAndClearTokenInformation();
//state.isClosed();
}catch (Exception e) {
Log.e(tag, "getUserIdMethod--->"+e);
}
}
}
});
}
}});
For Facebook use:
LoginManager.getInstance().logOut();
to logout.
did you tried to call it on separate thread:
public void logout()
{
new Thread(){
public void run() {
try {
mFacebook.logout(your_current_class_name.this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}

Add Data to post on facebook wall in android not displaying any message to post

I am using the following code and trying to post message on facebook wall along with the picture url. Both message and picture url is empty. Can any one find out and direct me in the right direction?
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
public void postToWall() {
Bundle params = new Bundle();
params.putString("message","test to post");
params.putString("url", URLEncoder.encode("http://a.espncdn.com/photo/2010/0523/pg2_a_cricket_576.jpg"));
try {
String response = facebook.request("me/feed", params, "POST");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
set this permission as public
private String[] PERMISSIONS = new String[]
{ "publish_stream", "read_stream", "offline_access" };
This will check is session exist if yes then it will direct update if not then ask user permission to update on wall.
Button click event
facebookConnector = new FacebookConnector(APP_ID, activity.getParent(),
activity.getApplicationContext(),PERMISSIONS);
if (facebookConnector.getFacebook().isSessionValid())
{
postMessageInThread(position); // see method below
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
#Override
public void onAuthSucceed()
{
postMessageInThread(position);
}
#Override
public void onAuthFail(String error)
{
}
};
SessionEvents.addAuthListener(listener);
facebookConnector.login();
}
This will update your data on wall
private void postMessageInThread(final int position)
{
Thread t = new Thread()
{
public void run()
{
try
{
facebookConnector.postMessageOnWall(
"Your Text Data",
"Your Email URL","Description");
mFacebookHandler.post(mUpdateFacebookNotification);
} catch (Exception ex)
{
Log.e("", "Error sending msg", ex);
}
}
};
t.start();
}
Note: : Here Position is my list record so manage your data according to that.

integrate yahoo messenger with android app

i surfed net to find some code snippet or some help to integrate yahoo messenger in android application. i could not find some thing helpful.
Please Help me by providing some link, tutorial or code sample so that i could integrate the yahoo messenger.
Thanks
Finally got solution for yahoo messenger integration i used openymsg a library and using below link
http://edwin.baculsoft.com/2011/11/creating-a-simple-yahoo-messenger-auto-response-with-java-and-openymsg-library/
changed my code in activity as below worked like a charm :)
public class SimpleYahoo extends Activity implements SessionListener{
/** Called when the activity is first created. */
private Logger logger = Logger.getAnonymousLogger();
private Session session = new Session();
Button sendButton;
boolean isLoginsuccess;
ListView resultTextView;
EditText editText;
Handler handler;
ArrayList<String> replymessage;
String reply;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replymessage=new ArrayList<String>();
try {
session.login("yahooid", "password");
} catch (AccountLockedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LoginRefusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FailedLoginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.addSessionListener(this);
sendButton=(Button) findViewById(R.id.button);
resultTextView=(ListView) findViewById(R.id.result);
editText=(EditText) findViewById(R.id.input);
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
doLogin();
}
});
handler=new Handler()
{
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what==0)
{
replymessage.add(reply);
setListAdapter();
}
}
};
}
private void doLogin() {
try {
// insert your yahoo id
// as for this example, im using my yahoo ID "dombaganas"
session.sendMessage("targetyahooid", editText.getText().toString());
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
#Override
public void dispatch(FireEvent fe) {
// TODO Auto-generated method stub
ServiceType type = fe.getType();
SessionEvent sessionEvent = fe.getEvent();
if (type == ServiceType.MESSAGE) {
try {
// log request message
reply=sessionEvent.getMessage();
Log.i("message","message from " + sessionEvent.getFrom() + " \nmessage " + sessionEvent.getMessage() );
// give an automatic response
// session.sendMessage(sessionEvent.getFrom(), "hi, you are sending " + sessionEvent.getMessage());
// session.
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
}
public void setListAdapter()
{
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.multi_line_list_item,replymessage);
resultTextView.setAdapter(arrayAdapter);
resultTextView.setSelection(replymessage.size()-1);
}
}

Categories

Resources