Sharing content on Facebook at onClick in RecyclerView - android

I am trying to share the app content on facebook in an onClick method inside RecyclerView. Recyclerview works fine and showing data properly before the onclick method.
All the dependencies and other stuff is being done in gradle file etc... The problem i am facing is as soon as the user clicks share button, new intent is generated, I am passing relevant parameters but activity doesn't perform any action.
Below is the code for opening Facebook(HomeActivity) onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.home);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
imageURL= null;
position=0;
} else {
imageURL= extras.getString("imageURL");
//position = extras.getInt("position");
}
} else {
imageURL= (String) savedInstanceState.getSerializable("imageURL");
//position= (int) savedInstanceState.getSerializable("position");
}
callbackManager = CallbackManager.Factory.create();
// loginDataBaseAdapter = new LoginDataBaseAdapter(this);
// loginDataBaseAdapter = loginDataBaseAdapter.open();
facebookLogin = (LoginButton) findViewById(R.id.login_button);
facebookLogin.registerCallback(callbackManager, callback);
}
And this is what I am doing during call back method, it login successfully but crashes afterwards.
public FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// Toast.makeText(getApplicationContext(),"On facebook",Toast.LENGTH_LONG).show();
AccessToken accessToken = loginResult.getAccessToken();
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(imageURL))
.build();
ShareDialog.show(HomeActivity.this, content);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Profile profile = Profile.getCurrentProfile();
textView.setText("Connection Lost ! Pleasr Try Again :" + profile.getName());
}
};
And this is how onClick() method is written:
#Override
public void onClick(View v) {
Intent intent = new Intent(context.getApplicationContext(),HomeActivity.class);
intent.putExtra("position",getAdapterPosition());
intent.putExtra("imageURL",uri);
context.startActivity(intent);
}
Can somebody guide me through this. I am not very experienced in making apps and sharing content on social apps. Any help would be highly appreciated.

You can directly share on facebook by using
try {
Intent intent1 = new Intent();
intent1.setClassName("com.facebook.katana", "com.facebook.katana.activity.composer.ImplicitShareIntentHandler");
intent1.setAction(Intent.ACTION_SEND);
intent1.setType("text/plain");
intent1.putExtra(Intent.EXTRA_TEXT, "any text");
startActivity(intent1);
} catch (Exception e) {
Intent intent = new Intent(Intent.ACTION_SEND);
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + "any constant";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
intent.putExtra(Intent.EXTRA_TEXT, "any text");
startActivity(intent);
}
i.e. try to share on facebook app. if the app is not installed on device the share will be opened on browser

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...

How do I use SharedPreferences with Facebook SDK?

Currently this is how my FB login looks like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TAG = "Login.Activity";
//Callback manager manages callbacks into the FB SDK from an Activity's onActivityResult() Method.
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
//If login in successful,
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
goMainScreen(profile);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(),R.string.cancel_login, Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), R.string.error_login, Toast.LENGTH_LONG).show();
}
});
}
private void goMainScreen(Profile profile) {
if(profile != null){
//Passing in the name,id and photo from the profile.
Intent intent = new Intent(this, MainActivity.class);
// intent.putExtra("name",profile.getName());
intent.putExtra("id",profile.getId());
intent.putExtra("photo",profile.getProfilePictureUri(200,200));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
//All Request Code, Result Code, and data are recieved by the activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
}
I would like to keep track of the user session throughout other activities and know if they have logged in before.Would I use sharedpreferences for this? If so will I be doing this at the beginning of the loginActivity?
Well you could use what provide the SDK and create a method like this one :
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}

ShareDialog doesn't open facebook app

Trying to implement facebook sharing, however it only works in webview if I set ShareDialog.Mode.AUTOMATIC, if I set it to NATIVE then nothing shows up at all and I don't receive no error callback. Facebook app is installed in the emulator.
Provider in manifest:
<provider android:authorities="com.facebook.app.FacebookContentProvider{myAppId}"
android:name="com.facebook.FacebookContentProvider"
android:exported="true"/>
Code for sharing:
public void share(String contentUrl,
Activity activity){
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(contentUrl))
.build();
ShareDialog dialog = new ShareDialog(activity);
dialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
EventBus.getDefault().post(new ShareEvent(true));
}
#Override
public void onCancel() {
Log.e(TAG, "Facebook Share Cancel");
EventBus.getDefault().post(new ShareEvent(false));
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "Facebook share error: " + error.getMessage());
EventBus.getDefault().post(new ShareEvent(false));
}
})
dialog.show(content, ShareDialog.Mode.NATIVE);
}
I'm calling share(..) method from fragment.
I tried implementing sharing using intents, and that works
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://myUrl.com");
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ((app.activityInfo.name).contains("facebook")) {
final ActivityInfo mActivity = app.activityInfo;
final ComponentName name = new ComponentName(mActivity.applicationInfo.packageName, mActivity.name);
shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
shareIntent.setComponent(name);
activity.startActivity(shareIntent);
break;
}
}
However in my case I need successful share callback, which as much as I know my last solution doesn't provide, since it always return result CANCELED
Have you declared permission for it? Like below:
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions"); // permission.
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// do something here
finish();
}
#Override
public void onCancel() {}
#Override
public void onError(FacebookException exception) {}
});
This is my sample code: https://github.com/minhhuy150894/simple-puzzle/blob/master/app/src/main/java/xyz/davidng/puzzle/FacebookShareImage.java

Facebook is firing onCancel

I was reading the thread: Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User and I'm using exactly the same code to call a facebook login, but, is always firing the method onCancel, what I'm doing wrong?
public class LoginActivity extends AppCompatActivity {
CoordinatorLayout BackgroundImage;
int[] images = new int[] {R.drawable.bg01, R.drawable.bg02, R.drawable.bg03};
Button BtnIniciar;
TextView BtnRecuperar;
EditText txtCorreo;
EditText txtContrasena;
String androidId;
TextView btnRegistrar;
LoginButton loginButton;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
BackgroundImage = (CoordinatorLayout)findViewById(R.id.background);
int imageId = (int)(Math.random() * images.length);
BackgroundImage.setBackgroundResource(images[imageId]);
BtnIniciar = (Button) findViewById(R.id.Iniciar);
BtnRecuperar = (TextView) findViewById(R.id.btnRecuperar);
txtCorreo = (EditText) findViewById(R.id.txtCorreo);
txtContrasena = (EditText) findViewById(R.id.txtContrasena);
btnRegistrar = (TextView) findViewById(R.id.btnRegistrar );
androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Boolean isLogged = new HttpGetPost().IsLogged(androidId);
if(isLogged){
Intent intent = new Intent( LoginActivity.this, MainActivity.class);
startActivity(intent);
}
BtnIniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean result = new HttpGetPost().Login(txtCorreo.getText().toString(), txtContrasena.getText().toString(), 2, androidId);
if (result) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(v.getContext(), "El usuario/contraseña no es válido.", Toast.LENGTH_LONG).show();
}
}
});
BtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RecuperarContrasena.class);
startActivity(intent);
}
});
btnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegistroActivity.class);
startActivity(intent);
}
});
//MultiDex.install(this);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.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) {
Log.v("LoginActivity", response.toString());
// Application code
// String email = object.getString("email");
// String birthday = object.getString("birthday"); // 01/31/1980 format
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
return;
}
I found the error, the error was:
I was adding the key_hash into the fb_login_protocol_scheme and should be: fb12322222 because my APP ID is 12322222.

How to create dialog overlay of activity, while user login to facebook?

I am using this code to allow the user to log in to facebook when the application is opened. Once the user it loged in the application goes to the main menu.
public class facebook_social extends Activity implements LoginListener {
private FBLoginManager fbManager;
Intent intentResult;
Bitmap bmImg = null;
URL myFileUrl =null;
ImageView i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intentResult = new Intent(getApplicationContext(), MainMenu.class);
//If the sdk version is Honeycomb the take off strictMode to allow for network connection in main thread.
if(Build.VERSION.SDK_INT >= 11){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
shareFacebook();
}
public void shareFacebook() {
String permissions[] = { "read_stream", "user_relationship_details",
"user_religion_politics", "user_work_history",
"user_relationships", "user_interests", "user_likes",
"user_location", "user_hometown", "user_education_history",
"user_activities","offline_access"};
fbManager = new FBLoginManager(this,R.layout.black,"173174566087561",permissions);
if (fbManager.existsSavedFacebook()) {
fbManager.loadFacebook();
} else {
fbManager.login();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fbManager.loginSuccess(data);
}
public void loginFail() {
fbManager.displayToast("Login failed!");
}
public void logoutSuccess() {
fbManager.displayToast("Logout success!");
}
public void loginSuccess(Facebook facebook) {
GraphApi graphApi = new GraphApi(facebook);
User user = new User();
try {
user = graphApi.getMyAccountInfo();
} catch (EasyFacebookError e) {
e.toString();
}
String pkg = getPackageName();
intentResult.putExtra(pkg + ".myName", user.getName());
intentResult.putExtra(pkg + ".myId", user.getId());
startActivity(intentResult);
Intent i = new Intent();
i.putExtra("name", user.getName());
}
}
As you see here the application gives a black backgroud when at this screen to allow the user to log in. What i want to do is, have the log in over top of the main menu. How would i go about doing this?
Integrating it into the main menu activty?
Android is based on stacking Activities, so that's what you should do. You could use startActivityForResult to handle the login Activity and enable your main Activity when a positive result (=succesful login) is returned.

Categories

Resources