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.
Related
I am using facebook login into my application. Now I am facing one strange issue in my project LoginManager.getInstance().registerCallback not getting called.
I am using following codes:
FacebookSdk.sdkInitialize(getActivity());//It showing as deprecated now
AppEventsLogger.activateApp(getActivity());//It showing as deprecated now
callbackManager = CallbackManager.Factory.create();
muvattapuzha
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("eeeee");
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code not called
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,gender");
request.setParameters(parameters);
request.executeAsync();
}
OnActivity result method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
Note: I am using with Activity->fragment-> fragment.
Activity onResult method like
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
for (Fragment fragment1 : fragment.getChildFragmentManager().getFragments()) {
fragment1.onActivityResult(requestCode, resultCode, data);
Log.d("Activity", "ON RESULT CALLED");
}
}
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
What could be the issue here?
Use this code this is working fine for me.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<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" />
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
callbackManager = CallbackManager.Factory.create();
FacebookSdk.sdkInitialize(LoginMainActivity.this);
setContentView(R.layout.activity_login_main);
loginButton = findViewById(R.id.activity_main_btn_login);
loginButton.setBackgroundResource(R.drawable.fb_rounded_broder);
loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
loginButton.setCompoundDrawablePadding(0);
loginButton.setText("");
loginButton.setReadPermissions(Arrays.asList(new String[]{"email", "user_birthday", "user_hometown"}));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "User login successfully");
getProfile();
}
#Override
public void onCancel() {
// App code
Log.d(TAG, "User cancel login");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.d(TAG, "Problem for login");
}
});
public void getProfile() {
try {
accessToken = AccessToken.getCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.d(TAG, "Graph Object :" + object);
try {
String[] splitStr = object.getString("name").split("\\s+");
FBFirstname = splitStr[0];
FBLastName = splitStr[1];
FBEmail = object.getString("email");
FBUUID = object.getString("id");
Log.e(TAG, "firstnamev: " + splitStr[0]);
Log.e(TAG, "last name: " + splitStr[1]);
Log.e(TAG, "Email id : " + object.getString("email"));
Log.e(TAG, "ID :" + object.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,gender,email");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from
{
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
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();
}
});
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.
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);
}
}
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");