Callback while sending Tweet using TweetComposer? - android

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

Related

Intent activity after facebook login opened twice

I have a main activity that displays login option, if the user clicked login with FB button, I will call fblogin();, and if the login success then I will do intent to open home activity.
right now, the home activity seems to open twice. (i can see it appear twice, stacked)
private void Fblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("LoginActivity", response.toString());
Log.d("LoginActivity", object.toString());
String jsonresult = String.valueOf(object);
System.out.println("JSON Result" + jsonresult);
String str_firstname=null,str_id=null;
try {
str_firstname=object.getString("name");
str_id = object.getString("id");
String str_email = object.getString("email");
Intent home = new Intent(MainActivity.this , HomeActivity.class);
home.putExtra("name", str_firstname);
home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE);
startActivity(home);
} catch (JSONException e) {
e.printStackTrace();
Log.d("xxxx","aa");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
in my main activity, i call this in my on create FacebookSdk.sdkInitialize(getApplicationContext());
, iI also check for initial login status `
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);}
but I think that initial check has nothing to do with it becauseI tried to delete it too but it still happening.`
and in my Home Activity, I have not write any facebook related codes yet.
EDIT : I PUT WHOLE CODE (MainActivity)
import ...
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static Boolean IsLoggedFB = false; //general state of fb logged
public static Boolean IsLoggedManual =false; //status boolean if logged in by email (manual)
public static Boolean IsLoggedGM = false; //general state of google gmail logged
String ID_HNBS; //IDhnbs created when first Registered
String Email;
TextView Fpassword;
Button Daftar;
EditText email, password;
Button LoginEmail;
LoginButton fb_button;
SignInButton gplus_button;
MainActivity myContext;
static String personName;
private boolean mIntentInProgress;
FragmentManager fragmentManager;
private CallbackManager callbackmanager;
//for G+
private GoogleSignInOptions gso;
private static final int PROFILE_PIC_SIZE = 30;
private GoogleApiClient mGoogleApiClient;
private ConnectionResult mConnectionResult;
private boolean mSignInClicked;
static final int RC_SIGN_IN = 0;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
LinearLayout tv;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
public static final String MyPREFERENCES = "xpp";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
IsLoggedManual = sharedpreferences.getBoolean("IsLoggedManual", false); // get value of last login status
IsLoggedGM = sharedpreferences.getBoolean("IsloggedGM", false); // get value of last login GM
Daftar = (Button) findViewById(R.id.buttonDaftarEmail);
LoginEmail = (Button) findViewById(R.id.buttonLoginEmail);
fb_button = (LoginButton)findViewById(R.id.fblogin_button);
//Initializing google signin option
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
gplus_button = (SignInButton) findViewById(R.id.sign_in_button);
gplus_button.setSize(SignInButton.SIZE_STANDARD);
gplus_button.setScopes(gso.getScopeArray());
//Initializing google api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
//.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
Daftar.setOnClickListener(this);
LoginEmail.setOnClickListener(this);
fb_button.setOnClickListener(this);
gplus_button.setOnClickListener(this);
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
Log.d("TAG", "ACCESS TOKEN STATUS" + AccessToken.getCurrentAccessToken() + " --- profile=" + Profile.getCurrentProfile());
//CHECK IF ALREADY LOGGED BY FB
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
} else if ( IsLoggedManual ) { //IF already LOGGED IN MANUAL (SHAREDPREF)
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonDaftarEmail) {
Intent intent = new Intent(MainActivity.this, UserRegistration.class);
startActivity(intent);
} else if (v.getId() == R.id.buttonLoginEmail) {
Intent intent_signin = new Intent(MainActivity.this, LoginManual.class);
startActivity(intent_signin);
} else if (v.getId() == R.id.fblogin_button) {
Fblogin();
} else if (v.getId() == R.id.sign_in_button) //google sign in button
{
Intent intent_Gsignin = new Intent(MainActivity.this, GSignIn.class);
startActivity(intent_Gsignin);
}
}
private void onSignInClicked() {
// User clicked the sign-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mShouldResolve = true;
mGoogleApiClient.connect();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
private void Fblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
Log.d("LoginActivity", response.toString());
Log.d("LoginActivity", object.toString());
String jsonresult = String.valueOf(object);
System.out.println("JSON Result" + jsonresult);
String str_firstname=null,str_id=null;
try {
str_firstname=object.getString("name");
str_id = object.getString("id");
String str_email = object.getString("email");
Intent home = new Intent(MainActivity.this , HomeActivity.class);
home.putExtra("name", str_firstname);
home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE);
startActivity(home);
} catch (JSONException e) {
e.printStackTrace();
Log.d("xxxx","aa");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
//After the signing we are calling this function
private void handleSignInResult(GoogleSignInResult result) {
//If the login succeed
if (result.isSuccess()) {
//Getting google account
GoogleSignInAccount acct = result.getSignInAccount();
//tv= (LinearLayout) tv.findViewById(R.id.layoutfragmentlogin);
//tv.setVisibility(View.GONE); //hide include , so include now show nothing
Intent Home=new Intent(this,HomeActivity.class);
Home.putExtra("name",acct.getDisplayName());
Home.putExtra("email", acct.getEmail());
Home.putExtra("URL",acct.getPhotoUrl());
startActivity(Home);
} else {
//If login fails
Toast.makeText(this, "Login Failed on silentsign in", Toast.LENGTH_LONG).show();
}
}
//#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
Toast.makeText(myContext, "User is connected!", Toast.LENGTH_LONG).show();
}
//#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(callbackmanager!=null) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
Log.d("ani", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
}
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != this.RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
}
}
//#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
//prefs.edit().putBoolean("Islogin",false).commit();
//DO Nothing..
/*
//==========Below is Trying to connect if googleUser not connected already =======
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d("ani", "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e("ani", "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
}
}*/
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setTitle("HnBS Alert")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
EDIT 2 : MY HOMEACTIVITY CODE
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/**
* react to the user tapping/selecting an options menu item
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_menu_logout:
LoginManager.getInstance().logOut(); //LogOut from Facebook
//logout from login manual
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("IsLoggedManual",false).commit();
//if (mGoogleApiClient.isConnected()) {
// if (mGoogleApiClient.isConnected())
// Auth.GoogleSignInApi.signOut(mGoogleApiClient);
//}
Toast.makeText(this, "LoggedOut!", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
After eight hours trial with some debugging, i couldn't find any trace of what is causing my HomeActivity fires twice. for people who stuck in any similar case, if you want and if its not breaking out your code, you can try to make your activity appear only one instance by adding this on your activity declaration in the manifest:
android:launchMode = "singleTask"
this has been the solution for me right now cause i don't want to waste any time longer as i need to move on to the next progress. thank you for any assistance.
You are calling the activity twice. That is
when consider if you are logged in facebook and google then the both the code get executed.
in onCreate you are calling
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result); //check method for going to home activity
}
and
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
} else if ( IsLoggedManual ) { //IF already LOGGED IN MANUAL (SHAREDPREF)
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
Use these conditions as one eg
opr.isDone() || AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null
Here you missed it, check out this code -
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
Above cached sign-in will start HomeActivity as well as if your AccessToken is not null(you're logged in with facebook) - again will start Home Activity
//CHECK IF ALREADY LOGGED BY FB
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
Solution:
You should put these conditions using else if ladder statements...

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

Google+ Login Not working properly on Android fragment

I am working with google+ login to my application and when i done it using a activity its work charm and after that i move my code into a fragment and after that when i try to login to google+ its not working i have to open the fragment activity 2 times to login to the google+ can anyone tell me what happen the code to the fragment is added below
public class GooglePluseFragment extends Fragment implements
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
private static final String TAG = "MainActivity";
private static final int PROFILE_PIC_SIZE = 800;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut;
private Context mContext;
private Activity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
mContext = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.compund_google_pluse_fragment,
container, false);
btnSignIn = (SignInButton) view.findViewById(R.id.btn_sign_in);
btnSignOut = (Button) view.findViewById(R.id.btn_sign_out);
sharedPref = view.getContext().getSharedPreferences(
Constantz.SHEARED_PREFEREANCE, Context.MODE_PRIVATE);
mGoogleApiClient = new GoogleApiClient.Builder(view.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signInWithGplus();
}
});
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOutFromGplus();
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != Activity.RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
mActivity, 0).show();
Log.e(TAG, "" + result.getErrorCode());
return;
}
if (!mIntentInProgress) {
mConnectionResult = result;
if (mSignInClicked) {
Log.e(TAG, "" + result.getErrorCode());
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
getProfileInformation();
updateUI(true);
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(mActivity,
RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl + " user id:"
+ currentPerson.getId());
} else {
Toast.makeText(mContext, "Person information is null",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
}
this is how i added framgent in the fragment activity
pluseFragment = new GooglePluseFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.pluse_frame_layout, pluseFragment);
transaction.commit();
can somebody tell me what i have done wrong ? why i have to open the activity two times to login thank you
Finally found the answer, Problem was when the result activity call in the fragment was catch by the parent activity so you have to manually redirect the result to your fragment. Just have to add this line in your Parent Fragment Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GooglePluseFragment.RC_SIGN_IN) {
GooglePluseFragment fragment = (GooglePluseFragment) getSupportFragmentManager()
.findFragmentById(R.id.pluse_frame_layout);
fragment.onActivityResult(requestCode, resultCode, data);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Easy Solution for this ::
just create the static method in fragment
"
public static myOnActivityResult(int requestCode, int resultCode, Intent data){
.....Enter same code
}
and
call this method from Parant Activity on
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
.....
MyFragment.myOnActivityResult(requestCode,resultCode,data)
}
thats it

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