Facebook graph api android - 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

Related

Callback while sending Tweet using TweetComposer?

I am using fabric to integrate Twitter in Android application.
public class MainActivity extends AppCompatActivity {
private static final String TWITTER_KEY = "";
private static final String TWITTER_SECRET = "";
private TwitterLoginButton loginButton;
private Button btnPostTweet;
private static final int TWEET_COMPOSER_REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
btnPostTweet = (Button) findViewById(R.id.btn_post_tweet);
btnPostTweet.setOnClickListener(onClickListener);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Make sure that the loginButton hears the result from any
// Activity that it triggered.
if (requestCode == TWEET_COMPOSER_REQUEST_CODE && resultCode == RESULT_OK)
Toast.makeText(MainActivity.this, "Updated tweet using composer", Toast.LENGTH_SHORT).show();
else
loginButton.onActivityResult(requestCode, resultCode, data);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_post_tweet:
postTweet();
// postTweetManually();
break;
default:
break;
}
}
};
private void postTweet() {
/* TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("just setting up my Fabric.");
Intent twitterIntent = builder.createIntent();
startActivityForResult(twitterIntent, REQUEST_TWEET_POST);*/
Intent intent = null;
try {
intent = new TweetComposer.Builder(this)
.text("Tweet from Fabric!")
.url(new URL("http://www.twitter.com"))
.createIntent();
} catch (MalformedURLException e) {
e.printStackTrace();
}
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
}
private void postTweetManually() {
TwitterSession twitterSession = Twitter.getSessionManager().getActiveSession();
StatusesService statusesService = Twitter.getApiClient(twitterSession).getStatusesService();
String username = Twitter.getSessionManager().getActiveSession().getUserName();
statusesService.update("#" + username + "Manually update on twitter1", 1L, true, 0.0d, 0.0d, "", true, true, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
Toast.makeText(MainActivity.this, "Tweet Updated", Toast.LENGTH_LONG).show();
Log.d("Tweet Updated", result.data.user.name);
}
#Override
public void failure(TwitterException e) {
Log.d("Tweet Update Failed", e.getMessage());
}
});
}
}
I have not installed Twitter application in my device.
So TwitterComposer is opening WebBroswer.
After posted tweet I am getting screen like below which does not redirect to app.
Note : While login it works perfect..
Thanks.
Not sure if you have the same issue I had but in my case I was getting the onActivityResult() callback but the resulCode was not RESULT_OK although the tweet had been successfully posted

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

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.

Can't start another activity after Facebook login in android app

I have tried a lot to integrate facebook login in my android app. I have succeeded partially. Now my problem is I couldn't redirect to another activity after successful facebook login. I think it is because I called the activity not from a proper place. I mean I coudn't call activity before the session close. I have attached my code here.
public class FacebookLogin extends Activity {
private static List<String> permissions;
Session.StatusCallback statusCallback = new SessionStatusCallback();
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
// authButton.setFragment(this);
/***** FB Permissions *****/
permissions = new ArrayList<String>();
permissions.add("email");
/***** End FB Permissions *****/
authButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Check if there is any Active Session, otherwise Open New Session
Session session = Session.getActiveSession();
if(!session.isOpened()) {
session.openForRead(new Session.OpenRequest(FacebookLogin.this).setCallback(statusCallback).setPermissions(permissions));
} else {
Session.openActiveSession(FacebookLogin.this, true, statusCallback);
}
}
});
Session session = Session.getActiveSession();
if(session == null) {
if(savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if(session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
session.addCallback(statusCallback);
if(session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(permissions));
}
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
//Check if Session is Opened or not
processSessionStatus(session, state, exception);
}
}
#SuppressWarnings("deprecation")
public void processSessionStatus(Session session, SessionState state, Exception exception) {
if(session != null && session.isOpened()) {
if(session.getPermissions().contains("email")) {
//Show Progress Dialog
dialog = new ProgressDialog(FacebookLogin.this);
dialog.setMessage("Loggin in..");
dialog.show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (dialog!=null && dialog.isShowing()) {
dialog.dismiss();
}
if(user != null) {
Map<String, Object> responseMap = new HashMap<String, Object>();
GraphObject graphObject = response.getGraphObject();
responseMap = graphObject.asMap();
Log.i("FbLogin", "Response Map KeySet - " + responseMap.keySet());
// TODO : Get Email responseMap.get("email");
String fb_id = user.getId();
String email = null;
String name = (String) responseMap.get("name");
if (responseMap.get("email")!=null) {
email = responseMap.get("email").toString();
//TODO Login successfull Start your next activity
Intent intent = new Intent(FacebookLogin.this, UserAccount.class);
/*Sending some arguments*/
Bundle bundle = new Bundle();
bundle.putString("UserName",name );
bundle.putString("Id", email);
intent.putExtras(bundle);
startActivity(intent);
}
else {
//Clear all session info & ask user to login again
Session session = Session.getActiveSession();
if(session != null) {
session.closeAndClearTokenInformation();
}
}
}
}
});
} else {
session.requestNewReadPermissions(new Session.NewPermissionsRequest(FacebookLogin.this, permissions));
}
}
}
/********** Activity Methods **********/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FbLogin", "Result Code is - " + resultCode +"");
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
/*if(resultCode==RESULT_OK) {
Intent i = new Intent(FacebookLogin.this,UserAccount.class);
startActivity(i);
} */}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Save current session
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onStart() {
// TODO Add status callback
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
protected void onStop() {
// TODO Remove callback
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
Please help me..

Activity result no fragment exists for index after facebook publish

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

Categories

Resources