I want to import facebook birthdays of my friends to my app. Currently my app is capable of creating new birthday events. But its very long procedure to add each and every birthday, so instead I want a code to import all facebook friends birthdays to my app. I have used facebook session but get nothing much till now
facebook = new Facebook(Constants.FB_APP_ID);
Session session = new Session(getApplicationContext());
if (session.isOpened()) {
Toast.makeText(getApplicationContext(), session.getState().toString(),
Toast.LENGTH_LONG).show();
} else
Toast.makeText(getApplicationContext(), session.getState().toString(),
Toast.LENGTH_LONG).show();
fbRunner = new AsyncFacebookRunner(facebook);
Also i have created a request
private void importBirthdayFromFB() {
Toast.makeText(getApplicationContext(), "Clicked on fb button",
Toast.LENGTH_LONG).show();
fbRunner.request("maxparera/friends", new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public void onComplete(String response, Object state) {
String keys = "";
try {
JSONObject profile = new JSONObject(response);
// getting name of the user
Iterator<String> keysIterator = profile.keys();
if (keysIterator != null) {
while (keysIterator.hasNext()) {
keys += keysIterator.next().toString();
}
Toast.makeText(getApplicationContext(), keys, Toast.LENGTH_LONG).show();
}
final String name = profile.getString("name");
// getting name of the user
Toast.makeText(getApplicationContext(), Name: " + name, Toast.LENGTH_LONG).show();
} catch (final JSONException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
}
});
But I am not getting any name, instead getting exception, sating OAuthException
Please suggest me ASAP
Maybe your session dont have permission to get your friend's birthday.
You can request permission like below:
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_friends, read_friendlists));
Layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
</LinearLayout>
Note: I uses Facebook SDK 3.8, you can refer to its sample for more detail.
LoginButton is a component of Facebook SDK.
For full of my code:
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
Log.i(TAG, "session: " +session.toString());
Log.i(TAG, "state: " +state.toString());
if(exception!=null)
Log.i(TAG, "exception: " +exception.toString());
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
//REQUEST PERMISSION
authButton.setReadPermissions(Arrays.asList("user_friends, read_friendlists));
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
try{
Log.i(TAG, "Logged in...");
Log.i(TAG, "Execute my request");
Request r = new Request(session,"/me/friendlists",null,HttpMethod.GET,new Request.Callback() {
public void onCompleted(Response response) {
Log.i(TAG, "onCompleted");
try {
//I HAD FRIEND LIST
Log.i(TAG, "FRIEND: " + response.getGraphObject().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
r.executeAsync();
Log.i(TAG, "Finish my request");
}catch (Exception ex){
Log.e(TAG, ex.getMessage());
}
} else if (state.isClosed()) {
try{
}
catch(Exception ex){
ex.printStackTrace();
}
Log.i(TAG, "Logged out...");
}
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
Related
I'm a noob in android app. i am creating an application which sends app request to my facebook friends, using the method defined in https://developers.facebook.com/docs/android/send-requests.
now i'm having trouble logging in and accessing my app. after providing username and password, i'm logged into facebook and my facebook app asks for permission. after pressing ok, it is not redirecting to send request window, rather shows me the login window again as if i'm not logged in.
here's my full code. please help me.
invite_friends.xml
<Button
android:id="#+id/btn_fb_invite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_marginTop="54dp"
android:background="#drawable/button_click_color_white"
android:text="#string/btn_fb_invite"
/>
Invite.java
public class Invite extends FragmentActivity {
private Button pickFriendsButton;
private UiLifecycleHelper lifecycleHelper;
boolean pickFriendsWhenSessionOpened;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.hide();
setContentView(R.layout.invite_friends);
pickFriendsButton = (Button) findViewById(R.id.btn_fb_invite);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//onClickPickFriends();
if (ensureOpenSession()) {
sendRequestDialog();
}
else {
pickFriendsWhenSessionOpened = true;
}
}
});
lifecycleHelper = new UiLifecycleHelper(this, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
Toast.makeText(getApplicationContext(), "lifecycle helper", Toast.LENGTH_SHORT).show();
onSessionStateChanged(session, state, exception);
}
});
lifecycleHelper.onCreate(savedInstanceState);
// ensureOpenSession();
}
public void contactInvite(View view)
{
Intent intent = new Intent(getApplicationContext(),FindPhnFriends.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
private boolean ensureOpenSession()
{Toast.makeText(this, "ensure open session method", Toast.LENGTH_SHORT).show();
if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened())
{Toast.makeText(this, "no active session or active session is opened", Toast.LENGTH_SHORT).show();
Session.openActiveSession(Invite.this, true, new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{Toast.makeText(getApplicationContext(), "open active session", Toast.LENGTH_SHORT).show();
onSessionStateChanged(session, state, exception);
}
});
return false;
}
return true;
}
private void onSessionStateChanged(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
pickFriendsWhenSessionOpened = false;
Toast.makeText(getApplicationContext(), "session state changed", Toast.LENGTH_SHORT).show();
sendRequestDialog();
}
else
{
Toast.makeText(this, "session state not changed", Toast.LENGTH_SHORT).show();
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message", "Learn how to make your Android apps social");
WebDialog requestsDialog = (
new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
Toast.makeText(getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Network Error",
Toast.LENGTH_SHORT).show();
}
} else {
final String requestId = values.getString("request");
if (requestId != null) {
Toast.makeText(getApplicationContext(),
"Request sent",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
})
.build();
requestsDialog.show();
}
}
i found and answer to my question, here it is:
in ensureOpenSession method,
replace the condition with
if (Session.getActiveSession() != null || Session.getActiveSession().isOpened())
and in onSessionStateChanged method,
replace
if (state.isOpened())
with
if (session.isOpened() && state.isOpened())
I need to ask at the user to authorize publish permission if he dont do it.
I do it with this row of code:
//Into ShareOnFacebookFragment
Session.getActiveSession().requestNewPublishPermissions(new NewPermissionsRequest((SocialSharingActivity)getActivity(), "publish_actions"));
SocialSharingActivity is the Activity related to my Fragment (ShareOnFacebookFragment).
When I run the application the app correctly ask me the publish permission and I accept, but when I do publish I have this error in my logcat:
12-11 12:17:27.277: E/AndroidRuntime(29125): Caused by: java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.
Honestly my only hypotesis is that requestNewPublishPermissions run Async in background and then I have the problems when I try to publish. How I can solve this problem ? I post also my Entire fragment code
private final String TAG = "ShareFragment";
private UiLifecycleHelper uiHelper;
// To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the
// Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in
// order to communicate with the Activity.
private Session.StatusCallback callback = new Session.StatusCallback() { //Provides asynchronous notification of Session state changes.
#Override
public void call(Session session, SessionState state,Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
Log.i("CALLBACK: ", "Session state change: "+state);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
};
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
// try {
// mCallback = (OnHeadlineSelectedListener) activity;
// } catch (ClassCastException e) {
// throw new ClassCastException(activity.toString()
// + " must implement OnHeadlineSelectedListener");
// }
//}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
};
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
uiHelper.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
RelativeLayout myRelative = (RelativeLayout) inflater.inflate(R.layout.share_frame, container, false);
shareButton = (Button) myRelative.findViewById(R.id.shareButton);
workoutIdTextView = (TextView) myRelative.findViewById(R.id.workoutIdTextView);
objectCreatedTextView = (TextView) myRelative.findViewById(R.id.objectCreatedTextView);
actionCreatedTextView = (TextView) myRelative.findViewById(R.id.actionCreatedTextView);
return myRelative;
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
Log.i(TAG, "ONACTIVITYCREATED");
SocialSharingActivity caller =(SocialSharingActivity) getActivity();
Log.w(TAG, "caller "+caller.toString());
workoutIdTextView.setText(String.valueOf(caller.getWorkoutId()));
Log.i(TAG, "Data course " + caller.getEwCourse().toString());
Log.i(TAG, "Message Run " + caller.getEwRun().toString());
ewCourseFrag = caller.getEwCourse();
ewRunFrag = caller.getEwRun();
parAct=new Bundle();
parAct.putAll(ewRunFrag.getParams());
parObj = new Bundle();
parObj.putString("access_token", APP_ACCESS_TOKEN);
gson = new Gson();
parObj.putString("object", gson.toJson(ewCourseFrag));
publishSession = Session.getActiveSession();
//------------------------------Batch HTTP request-----------------------------------------------------------------------------------------------------------------
//
//------------------------------Declaration--and--implementation--of--Callback-----------------------------------------------------------------------------------------------------------------
RequestBatch.Callback batchCallback= new RequestBatch.Callback() {
#Override
public void onBatchCompleted(RequestBatch batch) {
Log.w(TAG, "Batch completed: "+ "OK");
//
}
};
//
Request.Callback reqCreateObjCallback= new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError() == null){
Log.w(TAG,"reqCreateObjCallback: "+ "OK");
objectCreatedTextView.setText("OK object");
}
else {
Log.e(TAG,"reqCreateObjCallback: "+ response.getError().toString());
Log.d(TAG, response.getError().getCategory().toString());
objectCreatedTextView.setText(response.getError().getCategory().toString());
}
//400
}
};
//
Request.Callback reqPublishCallback= new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError() == null) {
Log.w(TAG, "reqPublishCallback: "+ "OK");
actionCreatedTextView.setText("OK action");
// Toast.makeText(context, "ACTION_CREATED", Toast.LENGTH_LONG).show();
}
else {
Log.e(TAG, "reqPublishCallback: "+ response.getError().toString());
Log.d(TAG, response.getError().getCategory().toString());
actionCreatedTextView.setText(response.getError().getCategory().toString());
}
}
};
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------Create--instance--of--RequestBatch--------------------------------------------------------------------------------------------------------
RequestBatch requestBatch= new RequestBatch();
//------------------------------Request--for-create-the-graph-object---------------------------------------------------------------------------------------------------------------
Request reqCreateObj= new Request(
publishSession,
"app/objects/fitness.course",
parObj,HttpMethod.POST); //Create a Request for a common ObiectGraph of type course
reqCreateObj.setCallback(reqCreateObjCallback); //Set the callback for the Request
reqCreateObj.setBatchEntryName("objectCreate"); //Tag the request name into the Batch with "objectCreate"
requestBatch.add(reqCreateObj); //Add the request to the batch
//------------------------------Request-for-publish-action-------------------------------------------------------------------------------------------------------------------------------
parAct.putString("course",
"{result=objectCreate:$.id}"); //Use the tag to retrieve the informations about the graph object created
//can also add scrape flag to update the object
// par2.putString("end_time", new Date(new Date().getTime()+1000*60*2).toString()); // live text test
Request reqPublish =
new Request(publishSession, //Create a request for publish an action relative to the object;
// Similarly at a phrase, an action is like "verbo", graph object
"me/fitness.runs/",parAct, //is like "complemento oggetto" and the the user is "soggetto"
HttpMethod.POST); //
reqPublish.setCallback(reqPublishCallback); //Set the callback for the Request
requestBatch.add(reqPublish); //Add the request to the batch
requestBatch.addCallback(batchCallback); //Set the callback for the Batch Request
//Check network session opened and permissions
//codice sospeso
if(Session.getActiveSession().isOpened() && hasPublishPermission() && isNetworkAvailable()) {
Toast.makeText(getActivity(), "Session is opened, I have permission, Network is On", Toast.LENGTH_LONG).show();
requestBatch.executeAsync();
}
else if (Session.getActiveSession().isOpened() && isNetworkAvailable()){
Toast.makeText(getActivity(), "I dont have Permissions: " + Session.getActiveSession().getPermissions(), Toast.LENGTH_LONG).show();
Session.getActiveSession().requestNewPublishPermissions(new NewPermissionsRequest((SocialSharingActivity)getActivity(), "publish_actions"));
Toast.makeText(getActivity(), "Permissions: " + Session.getActiveSession().getPermissions(), Toast.LENGTH_LONG).show();
}
else if (Session.getActiveSession().isOpened() && hasPublishPermission()) {
Toast.makeText(getActivity(), "Check your status connection.", Toast.LENGTH_LONG).show();
}
else {
Intent loginIntent = new Intent((SocialSharingActivity)getActivity(),FbLoginActivity.class);
startActivity(loginIntent);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
}
I am using Facebook in my android app and it work just fine.
However, i realize that useless screen appears when i login every time saying that "you have already-authorized to this app" with OK and Cancel option.
How can i avoid or remove this screen from my app.
I searched on Google and i found some answer for older Facebook SDK But how to achieve it with new Facebook SDK(3.0 and above)?
this is my code,
public void onClick(View v)
{
Bundle myParams = new Bundle();
myParams.putString("message", " DOWNLOAD THE 'Saragama' ANDROID APP FROM " + url_android.toString()
+ ". Fully integrated with Facebook and Twitter.");
myParams.putString("name", mSharingText.getText().toString());
myParams.putString("caption", "www.saragama.com");
myParams.putString("description", "Various religios music, chants, mantras, christian songs, islamic music, quran and more on saragama");
myParams.putString("link", "http://android.saragama.com");
myParams.putString("picture", albumImageURL);
if (PlusUtilities.isInternetConnected())
{
// ~post your data
Session session = Session.getActiveSession();
if (session != null)
{
MyLog.w("session state", session.getState().toString());
if (session.getState().equals(SessionState.OPENED) || session.getState().equals(SessionState.OPENED_TOKEN_UPDATED))
{
publishStory(myParams);
}
else
{
plusUtilities1.showAlertDialog("Please login first!");
}
}
else
{
plusUtilities1.showAlertDialog("Please login first!");
}
}
else
{
plusUtilities1.showAlertDialog("Problem occured with your internet connection!");
}
}
// Facebook Login-------------------------------------------------------------------------------------
private void loginToFacebook()
{
if (PlusUtilities.isInternetConnected())
{
Session session = Session.getActiveSession();
// if session is in exceptional state
if (session.getState() == SessionState.CLOSED_LOGIN_FAILED || session.getState() == SessionState.OPENING)
{
session.closeAndClearTokenInformation();
}
if (!session.isOpened() && !session.isClosed())
{
String[] PERMISSION_ARRAY_PUBLISH =
{"publish_actions" };
List<String> PERMISSION_LIST = Arrays.asList(PERMISSION_ARRAY_PUBLISH);
session.openForPublish(new Session.OpenRequest(FacebookActivity.this).setPermissions(PERMISSION_LIST).setCallback(
statusCallback1));
}
else
{
Session.openActiveSession(this, true, statusCallback1);
}
}
else
{
plusUtilities1.showAlertDialog("Please check your internet connection!");
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
// plusUtilities1.ShowToast("onActivityResult");
MyLog.i("onActivityResult requestCode :responsecode:session state", requestCode + ":" + responseCode + ":"
+ Session.getActiveSession().getState().toString());
switch (requestCode)
{
case MyRaagaLoginActivity.REQUEST_CODE_FACEBOOK_LOGIN:
if (responseCode == RESULT_OK)
{
MyLog.e("Login", "trying to facebook Login");
Session.getActiveSession().onActivityResult(Act1, requestCode, responseCode, data);
}
else
{
plusUtilities1.ShowToast("User access denied!");
}
break;
default:
MyLog.i("case:", "default");
break;
}
}
/**
* function to get active facebook session if already exist or create the new session
*
* #param savedInstanceState
* =check if Session exist and restored in bundle during onSaveInstanceState() system call
* #author DeepakD
*/
public void GetOrCreateFacebookActiveSession(Bundle savedInstanceState)
{
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
Session session = Session.getActiveSession();
// if session is null try to find if session is saved previously
if (session == null)
{
if (savedInstanceState != null)
{
session = Session.restoreSession(this, null, statusCallback1, savedInstanceState);
}
// if still session is null then create the new session
if (session == null)
{
session = new Session(this);
}
// set the created session as active session
Session.setActiveSession(session);
}
updateFBbutton();
}
/**
* set login or logout button
*/
private void updateFBbutton()
{
Session session = Session.getActiveSession();
if (session.isOpened())
{
FbLoginbtn.setText("FBLogout");
FbLoginbtn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
onClickFBLogout();
}
});
}
else
{
FbLoginbtn.setText("FBLogin");
FbLoginbtn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
loginToFacebook();
}
});
}
}
/**
* Logout from facebook
*/
private void onClickFBLogout()
{
Session session = Session.getActiveSession();
if (!session.isClosed())
{
session.closeAndClearTokenInformation();
plusUtilities1.ShowToast("Logout successful");
}
}
/**
* This class is used to fetch the current status of active session
*
* #author DeepakD
*
*/
private class SessionStatusCallback1 implements Session.StatusCallback
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
updateFBbutton();
plusUtilities1.DissmissPD();
MyLog.w("session state", session.getState().toString());
if(session.getState()==SessionState.CLOSED_LOGIN_FAILED)
{
//login failed
plusUtilities1.ShowToast("Unable to connect,please try later..");
session.closeAndClearTokenInformation();
}
if (session.getState()== SessionState.OPENED)
{
//login successful
plusUtilities1.ShowToast("Login successful");
}
}
}
/**
* actually post the data on facebook
*
* #param myParams
* Bundle of parameters to be post
*/
private void publishStory(Bundle myParams)
{
plusUtilities1.ShowPD("Sharing data...");
Session session = Session.getActiveSession();
if (session != null)
{
// Check for publish permissions
List<String> permissions = session.getPermissions();
try
{
if (!isSubsetOf(PERMISSIONS, permissions))
{
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
plusUtilities1.DissmissPD();
MyLog.w("post response", "" + response.toString());
if (response.getError() == null)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Toast.makeText(FacebookActivity.this, "JSON error " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(FacebookActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
Toast.makeText(FacebookActivity.this, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(FacebookActivity.this, "Posted successfully!",
Toast.LENGTH_LONG).show();
FlurryAgent.logEvent("Audio Facebook share -" + EventName);
}
}
else
{
plusUtilities1.showAlertDialog("Something went wrong while posting!");
}
}
};
MyLog.w("BUNDLE TO BE POSTED;", myParams.toString());
Request request = new Request(session, "/me/feed", myParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
public static boolean isSubsetOf(Collection<String> subset, Collection<String> superset)
{
for (String string : subset)
{
if (!superset.contains(string))
{
return false;
}
}
return true;
}
protected void onStart()
{
super.onStart();
MyLog.i("FacebookActivity", "onStart");
FlurryAgent.onStartSession(this, KeysCls.Flurry_Analytics_Key);
FlurryAds.displayAd(this, "AppCircle_Ads", linlayAdLayout);
if (PlusUtilities.isInternetConnected())
{
Session.getActiveSession().addCallback(statusCallback1);
}
else
{
plusUtilities1.showAlertDialog("Please check your internet connection and try again!");
}
}
/**
* convert post's simple text to text with links
*
* #param Name
* #param Link
* #return
*/
String wallpostWithLink(String Name, String Link)
{
jo = new JSONObject();
try
{
jo.put("name", Name);
jo.put("link", Link);
}
catch (Exception e)
{
e.printStackTrace();
}
return jo.toString();
}
#Override
protected void onStop()
{
super.onStop();
FlurryAgent.onEndSession(this);
}
Go to developers.facebook.com and in Settings-> Basic->Single Sign On -> YES
In facebook sdk 4.0 try to activate and deactivate app in onResume and onPause like this:
#Override
protected void onResume() {
super.onResume();
// update your UI
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
I am trying to login into the Facebook using Facebook sdk .But it not logging in .Its opening the dialog box but after getting the credentials its not working . If i install the Facebook app it opens the Facebook app but login is not completed i cant get the token and user id . I cant post the message to the wall also . But it displays the toast that "message successfully displayed" but it is not posted in the Facebook wall.
Code:
public boolean isSession() {
access_token = sp.getString(TOKEN, "x");
expires = sp.getLong(EXPIRES, -1);
Log.d("TAG", access_token);
if (access_token != null && expires != -1) {
facebook.setAccessToken(access_token);
facebook.setAccessExpires(expires);
}
return facebook.isSessionValid();
}
private class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
Log.d("TAG", "LoginONComplete");
token =facebook.getAccessToken();
token_expires = facebook.getAccessExpires();
Log.d("TAG", "AccessToken: " + token);
Log.d("TAG", "AccessExpires: " + token_expires);
savePrefs3(EXPIRES,token_expires);
savePrefs(TOKEN,token);
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);
Uid = json.getString("id");
savePrefs("UID", Uid);
final String name = json.getString("name");
} 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) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
howToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
please tell me where i am going wrong . after displaying a toast app gets closed. while loading the fb dialog if i touch the screen it either reloads or switching back to the app window.
Please give immediate reply
The Facebook object is depreciated.You can use the following code in your activity oncreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.facebook_dialog);
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user == null) {
Toast.makeText(LoginFacebook.this.getApplicationContext(),
"Facebook Error",
Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(LoginFacebook.this.getApplicationContext(),
user.getName()+" Logged in Successfully.",
T
Toast.LENGTH_LONG).show();
finish();
}
//login_fb.setEnabled(true);
//progress.setVisibility(View.INVISIBLE);
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
finish();
}
And use the following code in the Manifest.xml file under the application tag.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name" >
</activity>
After Loging in to post to wall you have to call this method...
private void publishStory(String user) {
try {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("message", messageToPost);
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (Exception e) {
Log.i("Test",
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
progress.setVisibility(View.INVISIBLE);
toastmessage="Posted Successfully";
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
toastmessage,
Toast.LENGTH_SHORT).show();
}
}
};
Request request = new Request(session, user+"/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
"Facebook Error",
Toast.LENGTH_SHORT).show();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
and declare the variables as..
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions","manage_pages","publish_stream");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
Not exactly the answer to your question, but if you are starting to develop your app: usage of Facebook object is deprecated in 3.x API.
In new API you should use Session object, along with UiLifecycleHelper
when I install my app via ADB via Eclipse, then the facebook logon as well as publishing to the wall of the user works (using facebook SDK 3.0), but when I package my app and then install that app, then the facebook logon does not work. I get the fragment with a logon button, when I push the logon button, then it shows the dialog that the app wants to have access to my public profile and friendlist. When I click ok it goes back to the fragment with the login button.
My question is: What should I change to make the facebook SDK integration work during deployment time as well?
my code of the fragment (erased non-relevant parts):
public class Fragment_shareFacebook extends SherlockFragment {
Context context; //context and fields:
View v;
private Button shareButton;
private MainActvityCommunicatorIntentBasedLeaveManagement intentleaveset;
private EditText toshareText;
private TextView textInstructionsOrLink, sharedText, fb_share_title_preview, fb_share_text_preview, sharesubsubtitle;
private ViewSwitcher switcher;
private LinearLayout fb_preview_keeper, mainlayoutholderfbshare, loggedinscreen;
String subject, content;
private boolean switched;
private UiLifecycleHelper uiHelper;
private static final int REAUTH_ACTIVITY_CODE = 100;
private UserSettingsFragment usersetting;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private Session.StatusCallback callback =
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/**
* empty constructor
*/
public Fragment_shareFacebook(){
}
#Override
/**
* initialize the intentleaveset to inform main that we have an intent based leave standing by
*/
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
intentleaveset=(MainActvityCommunicatorIntentBasedLeaveManagement) context;
}
#Override
/**
* get the content that needs to be shared, also retrieve the pendingPublishReauthorization if necessary
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setHasOptionsMenu(true);
uiHelper = new UiLifecycleHelper(this.getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
subject = getArguments().getString("subject");
content = getArguments().getString("text");
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
Session session = Session.getActiveSession();
this.onSessionStateChange(session, session.getState(), null);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REAUTH_ACTIVITY_CODE){
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onDestroyView(){
//note: we have to remove the fragment again!
try{
FragmentTransaction transaction = this.getActivity().getSupportFragmentManager().beginTransaction();
transaction.remove(usersetting);
transaction.commit();
}catch(Exception e){
}
super.onDestroyView();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
//hvg: dze even disecten.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_facebook_share, container, false);
textInstructionsOrLink = (TextView) v.findViewById(R.id.textInstructionsOrLink);
fb_share_title_preview= (TextView) v.findViewById(R.id.fbsharetitlepreview);
fb_share_text_preview= (TextView) v.findViewById(R.id.fbsharetextpreview);
sharesubsubtitle=(TextView) v.findViewById(R.id.sharesubsubtitle);
loggedinscreen=(LinearLayout) v.findViewById(R.id.loggedinscreen);
usersetting=(UserSettingsFragment) this.getActivity().getSupportFragmentManager().findFragmentById(R.id.userSettingsFragment);
//authButton = (LoginButton) v.findViewById(R.id.authButton);
shareButton = (Button) v.findViewById(R.id.shareButton);
//usernamefield= (TextView) v.findViewById(R.id.selection_user_name);
toshareText = (EditText) v.findViewById(R.id.toshareText);
fb_preview_keeper= (LinearLayout) v.findViewById(R.id.fb_preview_keeper);
mainlayoutholderfbshare = (LinearLayout) v.findViewById(R.id.mainlayoutholderfbshare);
switcher=(ViewSwitcher)v.findViewById(R.id.fb_switcher);
mainlayoutholderfbshare.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(toshareText.isFocused()){
Log.i("Focussed", "--" + event.getX() + " : " + event.getY() + "--");
if (toshareText.isFocused()) {
Rect outRect = new Rect();
toshareText.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
toshareText.clearFocus();
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
Log.i("X-Y coordinate", "--" + event.getX() + " : " + event.getY() + "--");
//Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
return false;
}
});
//toshareText.setText(content);
switcher=(ViewSwitcher) v.findViewById(R.id.fb_switcher);
sharedText=(TextView) v.findViewById(R.id.sharedText);
if(switcher.getDisplayedChild()==0){
switched=false;
}else{
switched=true;
}
//note that we need a custom onclicklistener to share the story to fb
shareButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
intentleaveset.setIntentleave(true);
publishStory();
}
});
//note to main: we are leaving with an intent!
intentleaveset.setIntentleave(true);
Log.d("fsf: leaveintent","settrue");
Session session = Session.getActiveSession();
SessionState state = Session.getActiveSession().getState();
onSessionStateChange(session, state, null);
return v;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
// Only make changes if the activity is visible
intentleaveset.setIntentleave(true);
Log.d("switcher-init", Integer.toString(switcher.getDisplayedChild()));
if (state.isOpened()) {
// If the session state is open:
// Show the authenticated fragment
shareButton.setVisibility(View.VISIBLE);
toshareText.setVisibility(View.VISIBLE);
fb_preview_keeper.setVisibility(View.VISIBLE);
LayoutParams params = fb_preview_keeper.getLayoutParams();
params.height=LayoutParams.WRAP_CONTENT;
params.width=LayoutParams.MATCH_PARENT;
fb_preview_keeper.setLayoutParams(params);
params=shareButton.getLayoutParams();
params.height=LayoutParams.WRAP_CONTENT;
params.width=LayoutParams.MATCH_PARENT;
shareButton.setLayoutParams(params);
params=toshareText.getLayoutParams();
params.width=LayoutParams.MATCH_PARENT;
params.height=LayoutParams.WRAP_CONTENT;
toshareText.setLayoutParams(params);
toshareText.setMinLines(3);
toshareText.setScroller(new Scroller(context));
toshareText.setVerticalScrollBarEnabled(true);
fb_share_title_preview.setText(subject);
fb_share_text_preview.setText(getString(R.string.facebook_share_subtitle).concat("\n \n").concat(content));
if(!switched){
textInstructionsOrLink.setText(getString(R.string.facebookexplanationafterlgoong));
}else{
textInstructionsOrLink.setText(getString(R.string.facebookexplanationaftershared));
if(switcher.getDisplayedChild()!=1){
switcher.showNext();
}
/*
if(switcher.getDisplayedChild()==1){
switcher.showPrevious();
}else{
switcher.showNext();
}
*/
}
params=loggedinscreen.getLayoutParams();
params.height=LayoutParams.WRAP_CONTENT;
loggedinscreen.setLayoutParams(params);
sharesubsubtitle.setFocusable(true);
sharesubsubtitle.requestFocus();
} else {
// If the session state is closed:
// Show the login fragment
if(switcher.getDisplayedChild()==1){
switcher.showPrevious();
}
switched=false;
shareButton.setVisibility(View.INVISIBLE);
//shareButton.setHeight(0);
toshareText.setVisibility(View.INVISIBLE);
//toshareText.setHeight(0);
//LayoutParams params = switcher.getLayoutParams();
//params.height=0;
//params.width=params.MATCH_PARENT;
//switcher.setLayoutParams(params);
//fb_preview_keeper.setVisibility(View.INVISIBLE);
//params = fb_preview_keeper.getLayoutParams();
//params.height=0;
//params.width=params.MATCH_PARENT;
//fb_preview_keeper.setLayoutParams(params);
LayoutParams params=loggedinscreen.getLayoutParams();
params.height=0;
loggedinscreen.setLayoutParams(params);
sharedText.setText("");
textInstructionsOrLink.setText(this.getResources().getString(R.string.facebookexplainbeforelogon));
}
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS)
.setRequestCode(REAUTH_ACTIVITY_CODE);
session.requestNewPublishPermissions(newPermissionsRequest);
//session.reauthorizeForPublish(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", subject);
postParams.putString("caption", getString(R.string.facebook_share_subtitle));
postParams.putString("description", content);
if(toshareText.getText()!=null){
postParams.putString("message", toshareText.getText().toString());
}else{
postParams.putString("message", " ");
}
postParams.putString("link", "http://www.thewonderweeks.com");
postParams.putString("picture", "www.thewonderweeks.com/apple-touch-icon-114x114.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse;
try{
graphResponse = response
.getGraphObject()
.getInnerJSONObject();
}catch (Exception e){
if(e.getMessage()!=null){
Log.d("errorinFBcallback", e.getMessage());
}
return ;
}
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i("errormessagefacebookfragmenthtingy",
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Log.d("post id of posted material", postId);
shareButton.setVisibility(View.INVISIBLE);
if(switcher.getDisplayedChild()!=1){
switcher.showNext();
}
switched=true;
sharedText.setText(getString(R.string.successhare).concat(" ").concat(toshareText.getText().toString()));
textInstructionsOrLink.setText(getString(R.string.facebookexplanationaftershared));
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
I assume you followed the facebook developers tutorial. If so, you use this command to produce your key
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
You must also create a key with release keystore and register it to facebook.