Activity result no fragment exists for index after facebook publish - android

I'm using Facebook sdk 3, and I have an fragment that has share button.
At first call it works.
At second call I got
06-24 10:24:47.430: W/FragmentActivity(2812): Activity result no fragment exists for index: 0x3face
After onActivityResult the fragment detached from the activity and I see the previous fragment from that activity.
Here is my code:
public class AboutFragment extends BaseFragment implements OnClickListener, Session.StatusCallback {
private static final String GA_CATEGORY = "About";
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private Button mShareEmailButton;
private Button mShareFacebookButton;
private Button mConatctUsButton;
private WebView mAboutText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_about, container, false);
mShareEmailButton = (Button) v.findViewById(R.id.buttonShareEmail);
mShareFacebookButton = (Button) v.findViewById(R.id.buttonShareFacebook);
mConatctUsButton = (Button) v.findViewById(R.id.buttonContactUs);
mAboutText = (WebView) v.findViewById(R.id.webViewAbout);
mAboutText.loadUrl("file:///android_asset/about.html");
mShareEmailButton.setOnClickListener(this);
mShareFacebookButton.setOnClickListener(this);
mConatctUsButton.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShareEmail:
GA_Handler.sendEvent(getActivity(), GA_CATEGORY, "Share_click", "Email");
shareViaEmail();
break;
case R.id.buttonShareFacebook:
GA_Handler.sendEvent(getActivity(), GA_CATEGORY, "Share_click", "FB");
checkFacebookLogin();
break;
case R.id.buttonContactUs:
GA_Handler.sendEvent(getActivity(), GA_CATEGORY, "Contact_us_click");
((BaseNavigationActivity)getActivity()).loadFragment(new ContactUsFragment());
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean isFacebookResponse =
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
if (isFacebookResponse) {
System.out.println("FB Response");
}
}
/**
* Login to FB if needed
*/
public void checkFacebookLogin() {
try {
logInToFacebook();
} catch (Exception e) {
e.printStackTrace();
}
}
private void logInToFacebook() {
String app_id = getString(R.string.app_id);
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = new Session.Builder(getActivity().getApplicationContext())
.setApplicationId(app_id)
.build();
session.addCallback(this);
Session.setActiveSession(session);
// Login
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this)
.setPermissions(PERMISSIONS)
.setCallback(this));
} else {
Session.openActiveSession(getActivity(), true, this);
}
}
#Override
public void call(Session session, SessionState state, Exception exception) {
System.out.println("ABOUT: " + state);
if (state == SessionState.OPENED) {
if(isAdded()){
publishFeedDialog();
}else{
System.out.println("Home activity not attached");
}
}
}
/**
* Publish to FB
*/
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", getString(R.string.fb_share_name));
params.putString("caption", getString(R.string.fb_share_caption));
params.putString("description", getString(R.string.fb_share_description));
params.putString("link", getString(R.string.fb_share_link));
params.putString("picture", getString(R.string.fb_share_picture));
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(), params)) //
.setOnCompleteListener(new WebDialog.OnCompleteListener() {
Context appContext = getActivity().getApplicationContext();
#Override
public void onComplete(Bundle values, FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
DebugToast.show(appContext, "Posted story, id: " + postId);
} else {
// User clicked the Cancel button
DebugToast.show(appContext, "Publish cancelled");
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
DebugToast.show(appContext, "Publish cancelled");
} else {
// Generic, ex: network error
DebugToast.show(appContext, "Error posting story");
}
logOut();
}
})
.build();
feedDialog.show();
}
/**
* Disconnect from facebook
*/
public void logOut() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
}
How to make it work correct?
A different solution also accepted
Thanks in advance

Related

Facebook graph api android

I am trying to fetch the user data using graph api but unable to do so. I know there are many answers available to this question but didn't get the one that will help me.
I am using facebook sdk v3.20.For authentication part I am using amazon cognito service. Here's my MainActivity code:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
/**
* Initializes the sync client. This must be call before you can use it.
*/
CognitoSyncClientManager.init(this);
btnLoginFacebook = (Button) findViewById(R.id.btnLoginFacebook);
btnLoginFacebook.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start Facebook Login
Session.openActiveSession(MainActivity.this, true,
MainActivity.this);
}
});
btnLoginFacebook.setEnabled(getString(R.string.facebook_app_id) != "facebook_app_id");
final Session session = Session
.openActiveSessionFromCache(MainActivity.this);
if (session != null) {
setFacebookSession(session);
}
Button btnWipedata = (Button) findViewById(R.id.btnWipedata);
btnWipedata.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Wipe data?")
.setMessage(
"This will log off your current session and wipe all user data. "
+ "Any data not synchronized will be lost.")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// clear login status
if (session != null) {
session.closeAndClearTokenInformation();
}
btnLoginFacebook
.setVisibility(View.VISIBLE);
if (mAuthManager != null) {
mAuthManager
.clearAuthorizationState(null);
}
CognitoSyncClientManager.getInstance()
.wipeData();
// Wipe shared preferences
AmazonSharedPreferencesWrapper.wipe(PreferenceManager
.getDefaultSharedPreferences(MainActivity.this));
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
}).show();
}
});
startActivity(new Intent(MainActivity.this, FacebookInfo.class));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
And this is my facebookinfo code for calling graph api:-
public class FacebookInfo extends Activity {
private static final String TAG = "MainActivity";
String get_id, get_name, get_gender, get_email, get_birthday;
private Session.StatusCallback fbStatusCallback = new Session.StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
// do something with <response> now
try {
get_id = user.getId();
get_name = user.getName();
get_gender = (String) user.getProperty("gender");
get_email = (String) user.getProperty("email");
get_birthday = user.getBirthday();
Log.d(TAG, user.getId() + "; " +
user.getName() + "; " +
(String) user.getProperty("gender") + "; " +
(String) user.getProperty("email") + "; " +
user.getBirthday() + "; " +
(String) user.getProperty("locale") + "; " +
user.getLocation());
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Exception e");
}
}
}
});
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fbinfo);
try {
openActiveSession(this, true, fbStatusCallback, Arrays.asList(
new String[]{"email", "user_location", "user_birthday",
"user_likes", "publish_actions"}), savedInstanceState);
} catch (Exception e) {
e.printStackTrace();
}
}
private Session openActiveSession(Activity activity, boolean allowLoginUI,
Session.StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
Session session = Session.getActiveSession();
Log.d(TAG, "" + session);
if (session == null) {
Log.d(TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
I want to integrate these two codes. I have tried making two different activities of these codes and calling the facebookinfo activity from MainActivity and after integrating in that way whenever I run my app it crashes.
So please can someone help me with this??? How to integrate these two codes to get the user details????
Here is the complete code to get Facebook profile details...
I have used Facebook SDK 4.4.0
public class MainActivity extends Activity {
LoginButton loginButton;
private CallbackManager callbackManager;
private ProgressDialog pDialog;
URL myurl;
String profilepic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(MainActivity.this);
setContentView(R.layout.activity_main);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays
.asList("public_profile, email, user_birthday, user_friends"));
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
new fblogin().execute(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class fblogin extends AsyncTask<AccessToken, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(AccessToken... params) {
GraphRequest request = GraphRequest.newMeRequest(params[0],
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.v("MainActivity", response.toString());
try {
String profile_pic = object.getString("id");
try {
myurl = new URL(
"https://graph.facebook.com/"
+ profile_pic + "/picture");
} catch (Exception e) {
e.printStackTrace();
}
profilepic = myurl.toString();
Log.v("Name", object.getString("first_name"));
Log.v("Email", object.getString("email"));
Log.v("Profile Pic Url", profilepic);
Log.v("Gender", object.getString("gender"));
} catch (JSONException jse) {
// session.logoutUser();
Log.e("fb json exception", jse.toString());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,email,gender");
request.setParameters(parameters);
GraphRequest.executeBatchAndWait(request);
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
// TODO Auto-generated method stub
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
In manifest file add this
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
Create the facebook appid and place it in strings.xml

Getting user date from Facebook session ? - Android

I'm trying get name and email from a facebook session opened. I want to get these informations an add in a EditText. When I try get these informations the Facebook is opened to type my login and password to access after this doesn't return the informations.
How can I do it ?
I'm trying this.
public class CadUsuarioFrag extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener{
private EditText etNome, etEmail, etSenha;
private ImageButton ibImage;
private Button btnSingUp;
private String pathImage;
private static final int RESULT_LOAD_IMAGE = 1;
private ProgressDialog progress;
private final String TAG = getClass().getSimpleName() + "->";
//radiogroup
private RadioGroup rgTipoCad;
//
private String nome = "";
private String email = "";
private String senha = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomDrawerLayout)getActivity()).getSupportActionBar().hide();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
pathImage = cursor.getString(columnIndex);
cursor.close();
}
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.form_cadusuario, container, false);
etNome = (EditText)view.findViewById(R.id.etNome);
etEmail = (EditText)view.findViewById(R.id.etEmail);
etSenha = (EditText)view.findViewById(R.id.etSenha);
ibImage = (ImageButton)view.findViewById(R.id.ibImage);
btnSingUp = (Button)view.findViewById(R.id.btnSingUp);
rgTipoCad = (RadioGroup)view.findViewById(R.id.rgTipoCad);
//listeners
rgTipoCad.setOnCheckedChangeListener(this);
ibImage.setOnClickListener(this);
btnSingUp.setOnClickListener(this);
etNome.requestFocus();
return view;
}
#Override
public void onClick(View v) {
if(v == ibImage){
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}else if(v == btnSingUp){
if(checkFields()){
addUsuario();
}
}
}
/** verifica se todos os campos foram informados para o insert */
private boolean checkFields(){
nome = etNome.getText().toString().trim();
email = etEmail.getText().toString().trim();
senha = etSenha.getText().toString().trim();
int selected = rgTipoCad.getCheckedRadioButtonId();
if(nome.length() == 0 || email.length() == 0 || senha.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
etNome.requestFocus();
etNome.selectAll();
return false;
}else{
return true;
}
}
private void addUsuario(){
progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
Usuario u = new Usuario(nome, email, senha, "1");
JsonObjectRequest app = new UsuarioDAO().addUsuario(u, new UsuarioAdapter(){
#Override
public void onUsuarioCadastrado(Boolean value) {
if(!value){
Toast.makeText(getView().getContext(), "Usuário não cadastrado", Toast.LENGTH_SHORT).show();
}else{
sucesso();
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
private void sucesso(){
AlertDialog.Builder alert = new AlertDialog.Builder(getView().getContext());
alert.setTitle("Guia Store");
alert.setMessage("Obrigado por se cadastrar\nEfetue agora seu login para acesso");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FragmentTransaction ft;
Fragment frag;
frag = new LoginFrag();
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fl, frag, "InicioFrag");
ft.commit();
removeFrag();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rbGuiaStore){
//Log.i(TAG, "rbGuiaStore selecionado");
etNome.setHint("Nome");
etEmail.setHint("Email");
etSenha.setHint("Senha");
etNome.requestFocus();
}else{
//Log.i(TAG, "rbFacebook selecionado");
etNome.setHint("Nome");
etEmail.setHint("Email facebook");
etSenha.setHint("Senha facebook");
etNome.requestFocus();
checkFacebookSession();
}
}
private void checkFacebookSession(){
// start Facebook Login
Session.openActiveSession(getActivity(), 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.newMeRequest(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(getView().getContext(), user.getName(), Toast.LENGTH_SHORT).show();
etNome.setText(user.getName());
Log.i("usuario", user.getName());
}
}
}).executeAsync();
}
}
});
}
/** remove o fragment da fila */
private void removeFrag(){
getActivity().getSupportFragmentManager().popBackStack();
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
super.onStop();
CustomVolleySingleton.getInstance(getView().getContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
You can do something like below.
Request.newMeRequest(session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (response != null)
{
try
{
String name = user.getName();
String email = (String) user.getProperty("email");
Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}).executeAsync();
P.S. Session should be opened before running this request. You can check sessionState through isOpened() method

Get friend list using latest facebook sdk in android

MainActivity.java
public class MainActivity extends ActionBarActivity {
RequestAsyncTask task = null;
private SharedPreferences preferences;
private String AccessToken = "";
private static final List<String> PERMISSIONS = Arrays
.asList("publish_actions");
private static final List<String> PERMISSIONSFRD = Arrays
.asList("user_friends");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private LoginButton btn_fb_login;
private UiLifecycleHelper uiHelper;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
private enum PendingAction {
NONE, POST_PHOTO, POST_STATUS_UPDATE
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
// Log.e("HelloFacebook", String.format("Error: %s",
// error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall,
Bundle data) {
// Log.e("HelloFacebook", "Success!");
}
};
private Button btn_share_fb;
Button btn_frds;
private boolean isShareProcess = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState
.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
System.out.println("Start");
Log.e("FB LOGIN--->", "----->Login");
setContentView(R.layout.activity_main);
preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
btn_share_fb = (Button) findViewById(R.id.btn_share_fb);
btn_frds = (Button)findViewById(R.id.btn_frds);
btn_frds.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFrdList();
}
});
btn_fb_login = (LoginButton) findViewById(R.id.btn_fb_login);
btn_fb_login.setReadPermissions(Arrays.asList("basic_info", "email",
"user_birthday", "user_location"));
btn_fb_login.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
// TODO Auto-generated method stub
MainActivity.this.user = user;
try {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session
.isOpened());
if (enableButtons && user != null) {
Log.e("-->", "" + session.getPermissions());
Log.e("fb user.getId", "" + user.getId());
Log.e("fb user.getFirstName",
"" + user.getFirstName());
Log.e("fb user.getMiddleName",
"" + user.getMiddleName());
Log.e("fb user.getLastName",
"" + user.getLastName());
Log.e("fb user.getUsername",
"" + user.getUsername());
Log.e("fb user.getBirthday",
"" + user.getBirthday());
Log.e("fb user.getLocation",
"" + user.getLocation());
Log.e("fb user.gender",
""
+ user.asMap().get("gender")
.toString());
Log.e("fb user email", "Email "
+ user.asMap().get("email"));
AccessToken = session.getAccessToken();
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(
GeneralClass.temp_isFbLoginShare, true);
PEDIT.commit();
setFbLoginDetails1();
} else {
// profilePictureView.setProfileId(null);
// greeting.setText(null);
// btn_fb_login.setVisibility(View.VISIBLE);
Log.e("FB--->", "----> NOT LOGIN");
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(
GeneralClass.temp_isFbLoginShare, false);
PEDIT.commit();
}
} catch (Exception e) {
e.printStackTrace();
// Log.e("error get facebook details-->",
// "error get facebook details");
}
handlePendingAction();
}
});
btn_share_fb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!FbSharing.checkUserFBLogin()){
if (preferences.getBoolean(
GeneralClass.temp_isFbLoginShare, false) == true) {
// publishFeedDialog();
/**
* original method
* */
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session
.isOpened());
if (enableButtons) {
publishStory();
isShareProcess = true;
} else {
// Log.e("error:",
// "please login again in facebook");
}
// share();
// getListofFacebookFriend();
} else {
GeneralClass.showToast("Please login with Facebook",
getApplicationContext());
btn_fb_login.setVisibility(View.VISIBLE);
}
}else if(FbSharing.checkUserFBLogin()){
try {
publishStory();
} catch (Exception e) {
// Log.e("error share facebook user",
// "error share facebook user");
e.printStackTrace();
}
}
}
});
setFbLoginDetails();
}
protected void setFbLoginDetails() {
if (FbSharing.checkUserFBLogin()) {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
} else if (preferences.getBoolean(GeneralClass.temp_isFbLoginShare,
false) == true) {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
} else {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
}
}
protected void setFbLoginDetails1() {
if (FbSharing.checkUserFBLogin()) {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
} else if (preferences.getBoolean(GeneralClass.temp_isFbLoginShare,
false) == true) {
btn_fb_login.setVisibility(View.VISIBLE);
btn_share_fb.setVisibility(View.VISIBLE);
} else {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
}
}
#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, dialogCallback);
}
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
// Call the 'activateApp' method to log an app event for use in
// analytics and advertising reporting. Do so in
// the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(this);
updateUI("onResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (pendingAction != PendingAction.NONE
&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI("onSessionStateChange");
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but
// we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_PHOTO:
// postPhoto();
break;
case POST_STATUS_UPDATE:
// postStatusUpdate();
break;
}
}
private void updateUI(String fromWhere) {
// Log.e("fromWhere", "" + fromWhere);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons && user != null) {
AccessToken = session.getAccessToken();
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(GeneralClass.temp_isFbLoginShare, true);
PEDIT.commit();
setFbLoginDetails();
} else {
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(GeneralClass.temp_isFbLoginShare, false);
PEDIT.commit();
}
}
public void share() {
try {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons) {
Bundle bundle = new Bundle();
bundle.putString("caption", "Harlem Shake Launcher for Android");
bundle.putString("description",
"Your android can do the Harlem Shake. Download it from google play");
bundle.putString("link",
"https://play.google.com/store/apps/details?id=mobi.shush.harlemlauncher");
bundle.putString("name", "Harlem Shake Launcher");
bundle.putString("picture", "http://shush.mobi/bla.png");
new WebDialog.FeedDialogBuilder(getApplicationContext(),
Session.getActiveSession(), bundle).build().show();
}
} catch (Exception e) {
// Log.e("error share on facebook", "error share on facebook");
e.printStackTrace();
}
}
#SuppressWarnings("unused")
private void publishFeedDialog() {
try {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons) {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption",
"Build great social apps and get more installs.");
params.putString(
"description",
"The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link",
"https://developers.facebook.com/android");
params.putString("picture",
"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
getApplicationContext(), Session.getActiveSession(),
params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the
// success
// and the post Id.
final String postId = values
.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(),
"Posted story, id: " + postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(
getApplicationContext()
.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(
getApplicationContext()
.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(
getApplicationContext()
.getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
}).build();
feedDialog.show();
}
} catch (Exception e) {
// Log.e("error share on facebook", "error share on facebook");
e.printStackTrace();
}
}
private boolean isSubsetOf(Collection<String> subset,
Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null) {
GeneralClass.showToast("Wait while we share in facebook",
getApplicationContext());
// 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("name", "Lolipop for Android");
postParams.putString("caption",
"Get better experience!");
postParams.putString("description",
"Get better experience!");
postParams.putString("link",
"https://developers.facebook.com/android");
postParams
.putString("picture",
"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
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 (JSONException e) {
Log.i("-->", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getApplicationContext(),
error.getErrorMessage(), Toast.LENGTH_SHORT)
.show();
isShareProcess = false;
} else {
Toast.makeText(
getApplicationContext(),
"Successfully Shared on Facebook, postid - "
+ postId, Toast.LENGTH_LONG).show();
isShareProcess = false;
new GetLists().execute();
}
task = null;
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
task = new RequestAsyncTask(request);
task.execute();
}
}
private void getFrdList() {
Session session = Session.getActiveSession();
if (session != null) {
GeneralClass.showToast("Wait while we get List",
getApplicationContext());
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONSFRD, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, PERMISSIONSFRD);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
new Request(
session,
"/me/friends",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
JSONObject graphResponse = response.getGraphObject()
.getInnerJSONObject();
Log.e("JSON RESPONSE---->", "FRIEND LIST--->"+ graphResponse.toString());
}
}).executeAsync();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (isShareProcess == false) {
if (task != null) {
// Log.e("back press", "wait for share");
} else {
task = null;
// Log.e("back press", "no wait for share");
super.onBackPressed();
}
}
}
}
above code is displaying following output when click on friends button:
FRIEND LIST--->{"summary":{"total_count":10},"data":[]}
i dont know how to get list of friends. i already did R&D for this. but nothing getting actual result. i know in latest sdk, its not possible to get all friends but only those who used your app. i also try to run my app with two different users who are both friends. but still not getting in result.
kindly help me in this problem.
Since v2.0, it is not possible to get a list of ALL friends anymore. You will only get those friends who authorized your App too. That is why "data" is empty.
See the changelog for more information: https://developers.facebook.com/docs/apps/changelog
Check out the large amount of other threads about that exact same issue too, especially this one offers additional information: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

Permission decline facebook sdk for android

Working on Facebook for android application. Unable to get publish permission.
When i request for permission it get added to decline permissions. Any suggestions.
public class MainActivity extends Activity implements OnClickListener {
private static final String PERMISSION_PUBLISH = "publish_actions";
private TextView textView;
private Button check;
private Button ask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView1);
check = (Button) findViewById(R.id.check_per);
ask = (Button) findViewById(R.id.get_per);
check.setOnClickListener(this);
ask.setOnClickListener(this);
findViewById(R.id.post).setOnClickListener(this);
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
session.refreshPermissions();
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
updateUi(user);
}
}).executeAsync();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Session session = Session.getActiveSession();
if (session != null) {
session.onActivityResult(MainActivity.this, requestCode, resultCode, data);
session.refreshPermissions();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
public void updateUi(GraphUser graphUser) {
textView.setText(graphUser.getFirstName());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.check_per:
checkForPermission();
break;
case R.id.get_per:
getPermission();
break;
case R.id.post:
post();
break;
default:
break;
}
}
private void checkForPermission() {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// --- Shows PEMISSION_PUBLISH in declined permission not in
// permission granted
List<String> permissions = session.getDeclinedPermissions();
showToast("size : " + permissions.size());
for (int i = 0; i < session.getDeclinedPermissions().size(); i++) {
showToast("Has permission : " + permissions.get(i));
}
}
}
private void getPermission() {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(MainActivity.this, PERMISSION_PUBLISH);
session.requestNewPublishPermissions(newPermissionsRequest);
}
}
private void post() {
Request.newStatusUpdateRequest(Session.getActiveSession(), "Status Update", new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response != null)
showToast(response.toString());
}
}).executeAsync();
}
}
You should go to app settings on developers.facebook.com to Status&Review tab and send request for Facebook review team, see https://developers.facebook.com/docs/apps/review/ for details.

How to get the user info. using the android facebook sdk?

if (state.isOpened()) {
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Display the parsed user info
}
}
});
}
I have tried follow the facebook doc to get the user info when at the onSessionStateChange function, the problem is , it is weird that I follow the offical doc and it shows
Request.executeMeRequestAsync is depreciate , so I wonder how to implement get the user info in latest facebook sdk 3.6 ? What I would like to do is get the user info if the user logined. Thanks a lot
Update:
Anyway I would also like to ask whether this way to implement login is correct? There are two place in my app need to login
The first one is inside a fragment
public class Home extends Fragment {
public View rootView;
public ImageView HomeBg;
public ImageView buttonLoginLogout;
public TextView chi;
public TextView eng;
public ColorStateList oldColor;
public SharedPreferences prefs;
public EasyTracker tracker = null;
//Facebook login
private Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
tracker = EasyTracker.getInstance(getActivity());
getActivity().getActionBar().hide();
rootView = inflater.inflate(R.layout.home, container, false);
buttonLoginLogout = (ImageView) rootView.findViewById(R.id.home_connectFB);
eng = (TextView) rootView.findViewById(R.id.btn_eng);
chi = (TextView) rootView.findViewById(R.id.btn_chi);
if (Utility.getLocale(getActivity()).equals("TC")) {
chi.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
oldColor = eng.getTextColors();
} else {
eng.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
oldColor = chi.getTextColors();
}
eng.setOnClickListener(setChangeLangListener("EN"));
chi.setOnClickListener(setChangeLangListener("TC"));
//Facebook login
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(getActivity(), null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(getActivity());
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}
updateView();
return rootView;
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
tracker.set(Fields.SCREEN_NAME, "Landing Page " + Utility.getLocale(getActivity()));
tracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
EasyTracker.getInstance(getActivity()).activityStop(getActivity());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
buttonLoginLogout.setImageResource(R.drawable.landing_btn_take_a_selfie);
buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((LandingPage)getActivity()).tabHost.setCurrentTab(2);
}
});
} else {
buttonLoginLogout.setImageResource(R.drawable.landing_btn_connect_facebook);
buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) { onClickLogin(); }
});
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(getActivity(), this, true, statusCallback);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
}
}
public OnClickListener setChangeLangListener(final String lang) {
OnClickListener changeLangListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
Configuration config = new Configuration(getResources().getConfiguration());
if (Utility.getLocale(getActivity()).equals("TC") && lang.equals("EN")) {
tracker.send(MapBuilder.createEvent("menu_click","language", "switchEN", null).build());
config.locale = Locale.ENGLISH;
chi.setTextColor(oldColor);
eng.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
} else if (Utility.getLocale(getActivity()).equals("EN") && lang.equals("TC")) {
tracker.send(MapBuilder.createEvent("menu_click","language", "switchTC", null).build());
config.locale = Locale.TRADITIONAL_CHINESE;
eng.setTextColor(oldColor);
chi.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
}
getResources().updateConfiguration(config,getResources().getDisplayMetrics());
onConfigurationChanged(config);
}
};
return changeLangListener;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().finish();
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(getActivity(),getResources().getString(R.string.app_id));
}
}
The other one is inside another activity
public class SharePicForm extends Activity {
private final String TAG = "SharePicForm";
public ImageView photoArea;
public ImageView sharePhotoBtn;
public EditText shareContent;
public Bitmap mBitmap;
public Context ctx;
public String shareTxt;
public String fileUri;
public static boolean isShowForm = true;
public ProgressDialog pd;
public EasyTracker tracker = null;
//Facebook share
private PendingAction pendingAction = PendingAction.NONE;
private enum PendingAction {
NONE, POST_PHOTO
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = EasyTracker.getInstance(this);
setContentView(R.layout.share_pic_form);
ctx = this;
Utility.setHeader(this,R.string.selfie_header,false);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, callback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(callback));
}
}
photoArea = (ImageView) findViewById(R.id.photo_area);
shareContent = (EditText) findViewById(R.id.share_content);
if (getIntent() != null) {
Intent intent = getIntent();
fileUri = (String) intent.getStringExtra("photo");
} else if (savedInstanceState != null){
mBitmap = (Bitmap) savedInstanceState.getParcelable("bitmap") == null ? null : (Bitmap) savedInstanceState.getParcelable("bitmap");
}
FileInputStream inputStream;
try {
File imgSelected = new File(fileUri);
if (imgSelected.exists()) {
inputStream = new FileInputStream(imgSelected);
mBitmap = Utility.decodeBitmap(inputStream, 1280, 960);
photoArea.setImageBitmap(mBitmap);
sharePhotoBtn = (ImageView) findViewById(R.id.share_submit);
sharePhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBitmap != null && FormValidation.hasText(shareContent)) {
try {
File imageToShare = saveBitmapToStorage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shareTxt = shareContent.getText().toString();
performPublish(PendingAction.POST_PHOTO);
//new FormSubmit(ctx,easyTracker).execute("shareImg",imageToShare, textToShare);
}
}
});
} else {
Toast.makeText(ctx, ctx.getResources().getString(R.string.get_photo_error), Toast.LENGTH_SHORT).show();
finish();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private File saveBitmapToStorage () throws IOException{
String path = Environment.getExternalStorageDirectory().toString();
File outputFile = new File(path, "temp.jpg");
FileOutputStream out = new FileOutputStream(outputFile);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
return outputFile;
}
//Facebook share
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(SharePicForm.this)
.setTitle(ctx.getResources().getString(R.string.error))
.setMessage(ctx.getResources().getString(R.string.get_permission_error))
.setPositiveButton(ctx.getResources().getString(R.string.close), null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they will succeed.
pendingAction = PendingAction.NONE;
if (previouslyPendingAction == PendingAction.POST_PHOTO)
postPhoto();
}
private void performPublish(PendingAction action) {
Log.d(TAG,"Perform publish");
Session session = Session.getActiveSession();
if (session != null) {
Log.d(TAG,"Session != null");
pendingAction = action;
if (hasPublishPermission()) {
Log.d(TAG,"Has permission");
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
Log.d(TAG,"Open session");
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, "publish_actions"));
return;
} else {
onClickLogin();
}
} else{
Log.d(TAG,"Session == null");
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(callback));
} else {
Session.openActiveSession(this, true, callback);
}
}
private void postPhoto() {
Log.d(TAG,"postPhoto: " + hasPublishPermission());
if (hasPublishPermission()) {
if (mBitmap != null) {
Request request = Request.newUploadPhotoRequest(
Session.getActiveSession(),mBitmap, new Request.Callback() {
#Override
public void onCompleted(Response response) {
pd.dismiss();
if (response.getError() == null) {
Utility.showDialog(ctx,"success_photo",tracker);
} else {
Log.d(TAG,response.getError().getErrorMessage());
Toast.makeText(ctx, response.getError().getErrorMessage(), Toast.LENGTH_LONG).show();
Utility.showDialog(ctx,"error",tracker);
}
}
});
Bundle params = request.getParameters();
if (shareTxt != null)
params.putString("message", shareTxt);
request.setParameters(params);
request.executeAsync();
pd = ProgressDialog.show(ctx, ctx.getResources().getString(R.string.sys_info),ctx.getResources().getString(R.string.publishing));
}
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("bitmap", mBitmap);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(callback);
EasyTracker.getInstance(this).activityStart(this);
tracker.set(Fields.SCREEN_NAME, "Image_entryForm " + Utility.getLocale(this));
tracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(callback);
EasyTracker.getInstance(this).activityStop(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(this,getResources().getString(R.string.app_id));
}
}
Should I implement the get user info code in all activities? thanks
Okay, Use below code.
//Define textview to print detail
TextView mfirstname, mlastname, middlename, mfullname, mbirthdate,
mfacebookLink, mfacebookId, mfacebookUnm, mgender, mEmail;
// Code to retrieve data from FB
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() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
mfirstname.setText(user.getFirstName());
mlastname.setText(user.getLastName());
middlename.setText(user.getMiddleName());
mfullname.setText(user.getName());
mbirthdate.setText(user.getBirthday());
mfacebookLink.setText(user.getLink());
mfacebookId.setText(user.getId());
mfacebookUnm.setText(user.getUsername());
String gender = user.asMap()
.get("gender").toString();
String email = user.asMap()
.get("email").toString();
mgender.setText(gender);
mEmail.setText(email);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});

Categories

Resources