Facebook is firing onCancel - android

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.

Related

Using Picasso to get Facebook profile picture at login

I have searched the internet high and low and cannot find a solution to this problem that works for me. When the user signs into the app using the facebook login button, I want to get their Facebook profile picture and use it as their profile picture in my app. I'm trying to use Picasso to get the picture from the Facebook URL. Here is my code as it is. I'm getting an error
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (getIntent().getBooleanExtra("EXIT", false)) {
}
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
loginButton = (LoginButton) findViewById(R.id.fb_login_btn);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken
oldAccessToken, AccessToken currentAccessToken) {
}
};
accessToken = AccessToken.getCurrentAccessToken();
if (AccessToken.getCurrentAccessToken() == null) {
loginButton.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Picasso.with(this) //I'm getting an error here "Picasso
cannot be applied"
.load("https://graph.facebook.com/" +
loginResult.getAccessToken().getUserId(); +
"/picture?type=large")
.into(profilePhoto);
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
{
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
}
finish();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancelled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Login Error",
Toast.LENGTH_SHORT).show();
}
});
} else {
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
this.finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
#Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
}
}
The problem is with this part
Picasso.with(this) //I'm getting an error here "Picasso
cannot be applied"
.load("https://graph.facebook.com/" +
facebook_id + "/picture?type=large")
.into(profilePhoto);
Here instead of 'this' you need to pass activity or application context.
If you are in activity then type 'YourActivityName.this' or if you are in fragment then use 'getActivity'.
If you are thinking why 'this' is not working then FYI 'this' here means anonymous inner class.
try this
loginButton.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken().getUserId();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
if (object.has("picture")) {
//String profilePicUrl="http://graph.facebook.com/"+object.getString("id")+"/picture?type=large";
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
profilePicUrl = profilePicUrl.replace("\\", "");
Picasso.with(YourActivity.this)
.load(profilePicUrl)
.into(profilePhoto);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
{
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
}
finish();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancelled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Login Error",
Toast.LENGTH_SHORT).show();
}
});

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;
}

Fetching user data using Facebook Android SDK

I want to fetch user data from Facebook using my app. I've written the code and it logs in the user but fails to fetch user data. Here's the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AccessToken accessToken = AccessToken.getCurrentAccessToken();
callbackManager = CallbackManager.Factory.create();
if (PrefUtils.getCurrentUser(getActivity()) != null) {
//dont ask for login
Intent homeIntent = new Intent(getActivity(), MainActivity.class);
startActivity(homeIntent);
Toast.makeText(getActivity(), "Intent", Toast.LENGTH_SHORT).show();
//getActivity().finish();
}
mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "onSuccess: " );
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG, "onCompleted: "+object );
Log.e("response: ", response + "");
try{
email = object.getString("email");
name = object.getString("name");
Toast.makeText(getActivity(), "onSuccess", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "welcome " + user.name+" "+name, Toast.LENGTH_LONG).show();
Intent intent=new Intent(getActivity(),MainActivity.class);
startActivity(intent);
Toast.makeText(getActivity(), "Intent", Toast.LENGTH_SHORT).show();
//getActivity().finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.e(TAG, "onCancel: " );
}
#Override
public void onError(FacebookException e) {
Log.e(TAG, "onError: " );
}
};
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_sign_in, null);
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setCancelable(false);
skip = (Button) rootView.findViewById(R.id.btn_skip);
loginButton = (LoginButton) rootView.findViewById(R.id.fb_login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends"));
loginButton.setFragment(this);
btnLogin = (TextView) rootView.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
Log.e(TAG, "onClick: ");
}
});
skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(Splash.intent);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
It logs the user but fails to get the data. On debugging, the log shows null mCallback.

How to open activity when login facebook success?

I have two activity, when I login facebook activity success. It will be auto open activity 2 and tranfer data and picture. But it not working. please help me!
The problem is how to call another activity right and transfer data after authorization succeed login facebook button. I've been reading other posts but there is no solution that helped me.
Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
login = (LoginButton)findViewById(R.id.login_button);
profile = (ProfilePictureView)findViewById(R.id.picture);
shareDialog = new ShareDialog(this);
share = (Button)findViewById(R.id.share);
details = (Button)findViewById(R.id.details);
login.setReadPermissions("public_profile email");
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
details_dialog = new Dialog(this);
details_dialog.setContentView(R.layout.dialog_details);
details_dialog.setTitle("Details");
details_txt = (TextView)details_dialog.findViewById(R.id.details);
email = (TextView) findViewById(R.id.email);
details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
details_dialog.show();
}
});
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(AccessToken.getCurrentAccessToken() != null) {
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
// profile.setProfileId(null);
// email.setText("");
}
}
});
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
//write your code here what to do when user logout
profile.setProfileId(null);
email.setText("");
}
}
};
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShareLinkContent content = new ShareLinkContent.Builder().build();
shareDialog.show(content);
}
});
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "onError: " + error.getMessage());
}
});
}
public void RequestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if (json != null) {
String text = "<b>Name :</b> " + json.getString("name") + "<br><br><b>Email :</b> " + json.getString("email") + "<br><br><b>Profile link :</b> " + json.getString("link");
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString("id"));
email.setText(json.getString("email"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
String emails=email.getText().toString();
intent.putExtra("emails", emails);
intent.putExtra("BitmapImage", profile);
startActivity(intent);
}
}
activiti2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
username = (TextView) findViewById(R.id.textView);
imageView = (ImageView) findViewById(R.id.imageView);
String value=getIntent().getStringExtra("emails");
username.setText(value);
}
Change your code like this:
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
String emails=email.getText().toString();
intent.putExtra("emails", emails);
intent.putExtra("BitmapImage", profile);
startActivity(intent);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "onError: " + error.getMessage());
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
I hope this would work.
Start your activity in onSuccess method.
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
}

Android Facebook - get null profile

First time with Facebook SDK. I can't get users profile. Its always null. What's wrong?
btnFbWidget = (LoginButton) findViewById(R.id.btnFbWidget);
btnFbWidget.setReadPermissions("public_profile");
// Callback registration
btnFbWidget.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
if (profile != null)
Toast.makeText(getApplicationContext(), "LogIN as " + profile.getName(), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "nulll", Toast.LENGTH_SHORT).show();
}
/*...*/
});
use this method also,.....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Try with this method.
Initialize facebook SDK firstly.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init facebook sdk and
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
//instantiate callbacks manager
mCallbackManager = CallbackManager.Factory.create();
btnFbWidget=(LoginButton)findViewById(R.id.login_button);
btnFbWidget.registerCallback(mCallbackManager, this);
btnFbWidget.setReadPermissions(Arrays.asList("user_status","email"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//manage login result
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
public void onSuccess(LoginResult loginResults) {
Toast.makeText(getApplicationContext(), "Success ",
Toast.LENGTH_LONG).show();
}
public void onCancel() {
}
public void onError(FacebookException e) {
}
And then to get the User Profile use this method.
private static String uid,email;
public void getUserProfile() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
Log.v("LoginActivity", response.toString());
try {
//and fill them here like so.
uid = object.getString("id");
email = object.getString("email")
} catch (JSONException e) {
e.printStackTrace();
}
getGroups();
}
});
// If you want to pass data to other activity.
Bundle parameters = new Bundle();
parameters.putString("userdata", "email");
request.setParameters(parameters);
request.executeAsync();
}
And do call this method getUserProfile() in your on create.
EDIT 1 :
Change in read permissions.
btnFbWidget.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
And accordingly you can get further information like.
String email = object.getString("email");
String birthday = object.getString("birthday");

Categories

Resources