Saving Facebook profile picture and username Android - android

I've been working on a simple app for android - and i'm trying to login using Single Sign-On using the Facebook Android SDK.
I'm trying to save the profile picture and username. I'm not quite sure what's wrong - but nothing seems to happen after I Sign In on Facebook.
Here's my code:
public class fbLogin extends Activity {
Facebook facebook = new Facebook("MY-APP-ID");
private SharedPreferences mPrefs;
public boolean flag=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fblogin_screen);
mPrefs=getPreferences(MODE_PRIVATE);
String acces_token=mPrefs.getString("acces_token",null);
long expires=mPrefs.getLong("acces_expires", 0);
if(acces_token!=null)
{
facebook.setAccessToken(acces_token);
}
if(expires!=0)
{
facebook.setAccessExpires(expires);
}
if(!facebook.isSessionValid())
{
facebook.authorize(this, new DialogListener() {
public void onComplete(Bundle values) {
flag=true;
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
public void onFacebookError(FacebookError error) {}
public void onError(DialogError e) {}
public void onCancel() {}
});
} else{
flag=true;
}
if(flag==true)
{
try {
JSONObject me = new JSONObject(facebook.request("me"));
String id=me.getString("id");
String userName=me.getString("username");
ImageView picture;
TextView usr = (TextView)findViewById(R.id.userName);
picture = (ImageView) findViewById(R.id.profilePicture);
URL image_value= new URL("http://graph.facebook.com/" + userName + "/pictures" );
Bitmap profPict=BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
picture.setImageBitmap(profPict);
usr.setText(userName);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
What am I doing wrong?

Change this
URL image_value= new URL("http://graph.facebook.com/" + userName + "/pictures" );
to this
URL image_value= new URL("http://graph.facebook.com/" + userName + "/picture" );

Put this:
if(flag==true)
{
try {
JSONObject me = new JSONObject(facebook.request("me"));
String id=me.getString("id");
String userName=me.getString("username");
ImageView picture;
TextView usr = (TextView)findViewById(R.id.userName);
picture = (ImageView) findViewById(R.id.profilePicture);
URL image_value= new URL("http://graph.facebook.com/" + userName + "/pictures" );
Bitmap profPict=BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
picture.setImageBitmap(profPict);
usr.setText(userName);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In it's own method called getInfo(), then in your dialog listener call getInfo() like so
facebook.authorize(this, new DialogListener() {
public void onComplete(Bundle values) {
flag=true;
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
//We're authorized so getInfo();
getInfo();
}
public void onFacebookError(FacebookError error) {}
public void onError(DialogError e) {}
public void onCancel() {}
});
Now, in the Facebook SDK, there's a class called Utility. Set LOGGING = true.
Give it another go and watch the logs. The logs from facebook may say there's a mismatch between your app hash and the facebook app. Copy the hash in the log, go to your facebook app, check the box for android application and paste the hash in the corresponding field.

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>

How to get Facebook user name in android app

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.

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
}

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