I am developing an app which can log in facebook and write post on my wall ..
I am using this tutorial : http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
it's working fine but eclipse tell me all of this methods are deprecated ..
Now how can i replace it with recent version ??
Thanks in advance :)
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) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.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
SharedPreferences.Editor 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
}
});
} else {
postOnWall(quote);
}
}
// ==============================================================================
public void postToWall() {
// 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() {
}
});
}
// ==============================================================================
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = facebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
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.
This is my login function:-
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
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(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
SharedPreferences.Editor 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
}
});
}
}
This my function to get facebook likes and attributes:
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
id=profile.getString("id");
// getting name of the user
name = profile.getString("name");
// getting email of the user
email = profile.getString("email");
//about=profile.getString(about);
bio=profile.getString(bio);
birthday=profile.getString(birthday);
gender=profile.getString(gender);
link=profile.getString(link);
locale=profile.getString(locale);
political=profile.getString(political);
quotes=profile.getString(quotes);
relationship_status=profile.getString(relationship_status);
relegion=profile.getString(relegion);
website=profile.getString(website);
Log.d("Name",name);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} 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) {
}
});
//Getting Facebook Like
Session session = Session.getActiveSession();
new Request(
session,
"/{id}/likes",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.d("Facebook Likes", response.toString());
}
}
).executeAsync();
/*Session session = Session.getActiveSession();
Request.Callback callback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
// response should have the likes
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.d("Facebook Likes", response.toString());
}
};
Request request = new Request(session, "me/likes", null, HttpMethod.GET, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();*/
ERROR:-
D/Request﹕ Warning: Sessionless Request needs token but missing either application ID or client token.
I am getting other attributes as
28959-29486/com.example.sensetest D/Profile﹕ {"id":"************","email":"***********","first_name":"***","gender":"male","last_name":"****","link":"****","locale":"en_US","middle_name":"Singh","name":"Rituraj Singh Rathore","timezone":5.5,"updated_time":"2015-03-22T11:01:08+0000","verified":true}
The problem is I am not able to get facebook likes of user who has logged in. I have tried also How to get user likes from Facebook with Android sdk 3.0.
But I didn't got desired result.
Help me regarding this, Where am i doing wrong. What should i do to make it right?
I tried to post on my wall a message by clicking on a button in my activity. I first logged in and i am able to get some of my personal information from facebook too. But, when i am trying to post something on wall. It is not working.
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", "Test Message");
parameters.putString("description", "test test test");
response = mFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
This is the function i am trying to post on to my wall.
Can anybody help me out.
Response from facebook:
{"error":{"message":"An active access token must be used to query information about the current user","type":"OAuthException","Code":2500}}
Code to login:
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) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.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
SharedPreferences.Editor 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
}
});
}
}
I want to update status on facebook by app ,so i have searched a lot but not able to update status on facebook ,i have imported facebook sdk3.15.0,it gives permission error in logcat.so let me know how is it possible to update status ,and it gives response null ,my code is
imgfacebook.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
loginToFacebook();
}
});
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) {
facebook.setAccessToken(access_token);
postToWall(CheckRating);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.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
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
postToWall(CheckRating);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
public void postToWall(final String msg) {
try {
// Bundle parameters = new Bundle();
// parameters.putString("message", "Text is lame. Listen up:");
// parameters.putString("name", "Name");
// parameters.putString("link", "http://www.google.com");
// parameters.putString("caption", "Caption");
// parameters.putString("description", "Description");
//
// String response = facebook.request("me/feed", parameters,
// "POST");
// Log.v("response", response);
Bundle parameters = new Bundle();
parameters.putString("message", "Text is lame. Listen up:");
parameters.putString("method", "stream.publish");
String response = facebook.request(parameters);
Log.v("response", response);
System.out.println("Response is ....." + response);
} catch (Exception e) {
System.out.println("Response is nulll......");
}
// post on user's wall.
}
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());
}
}
}
}