I need help regarding accessToken of the facebook, the problem here is when i try to call accessToken method it returns a null. Actually i want to post comments from my app to the specific page and get comments from the page-id where these posts are posted.
The problem i have got is when i try to post comment i get an error like this An active access token must be used to query information about the current user.
and when i tried to get comments i get this error An access token is required to request this resource
I need help as i got stuck here.
Thanks for the help!!
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
linearLayout2 = (LinearLayout) inflater.inflate(R.layout.second_fragment, container, false);
editText = (EditText) linearLayout2.findViewById(R.id.commentBox);
button = (Button) linearLayout2.findViewById(R.id.submitButton);
openfeed = (LinearLayout) linearLayout2.findViewById(R.id.fakebutton);
initInstances();
initCallbackManager();
refreshButtonState();
getAllComments();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle params = new Bundle();
params.putString("message", editText.getText().toString());
GraphRequest graphRequest = new GraphRequest(
accessToken,
"/me/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
System.out.println("Success: " + response);
}
}
);
graphRequest.executeAsync();
}
});
return linearLayout2;
}
private void initInstances() {
System.out.println("I am init");
openfeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithPublishPermissions(getActivity(), Arrays.asList("publish_actions,publish_pages,manage_pages,user_about_me"));
}
});
}
private void initCallbackManager() {
System.out.println("i am initCallbackManager");
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
refreshButtonState();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
private void refreshButtonState() {
System.out.println("refresh button state");
if (!isLoggedIn()) {
openfeed.setVisibility(View.VISIBLE);
} else {
openfeed.setVisibility(View.GONE);
}
}
private boolean isLoggedIn() {
accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public void getAllComments() {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{page-id}/feed",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
System.out.println("comments: " + response);
}
}
).executeAsync();
}
}
Related
I am working on a custom button which enable Facebook login. What I am coding gave me a result which I need to tap the button twice only it will start the activity.
I was trying to work on it through adjusting the position of startActivity() function in different way. And I found that I can make it to become initialization through placing the startActivity() function just after the finding of view for button bLogin.
Logically, it seems not right as no user will start to proceed to the next activity before login.
Any solution on this? Thank you in advance.
For your information, here are my MainActivity java code.
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
GraphRequest graphRequest;
com.facebook.login.LoginManager fbLoginManager;
Button bLogin;
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//new activity from login page
public void chatbox (View view){
final Intent intent = new Intent(this, tabviewChatbox.class);
fbLoginManager = com.facebook.login.LoginManager.getInstance();
callbackManager = CallbackManager.Factory.create();
bLogin = (Button) findViewById(R.id.bLogin);
//only start activity if login success
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
startActivity(intent);
finish();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
}
});
}
public void graphRequest(AccessToken accessToken) {
graphRequest = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("response", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,birthday,friends");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
//Function calling for integration of font awesome, can directly put icon inside default button by typing name
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(IconicsContextWrapper.wrap(newBase));
}
}
I would like to use Facebook login in my App. I have just registred app and added SDK to project. However, I tried to follow the tutorial from documentation but nothing worked (I need to get ID and email from profile and send to to my server).
Fragment
public class LoginFragment extends Fragment {
#BindView(R.id.ivLogo) ImageView ivLogo;
#BindView(R.id.email) EditText edEmail;
#BindView(R.id.password) EditText edPassword;
#BindView(R.id.btnFbLogin) LoginButton btnFbLogin;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
String email, password, ID;
User user;
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance() {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.i("success", "success");
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login_screen, container, false);
ButterKnife.bind(this, view);
btnFbLogin.setReadPermissions("email");
btnFbLogin.setFragment(this);
// Callback registration
btnFbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
((MainActivity) getActivity()).getSupportActionBar().hide();
}
private void FBcallback() {
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onCancel() { }
#Override
public void onError(FacebookException e) { }
};
btnFbLogin.setReadPermissions("email");
btnFbLogin.registerCallback(callbackManager, callback);
}
private void loginEmail() {
FactoryAPI.getInstanceLogin().login("hardcoded mail", "hardcoded password").enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), R.string.email_password_is_not_right, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
}
});
}
private void loginFB() {
FactoryAPI.getServieFBlogin().loginFB(email, ID).enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Log.e("error", "error");
}
});
}
public void getEmailPassword() {
email = edEmail.getText().toString();
password = edPassword.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(getContext(), R.string.empty_properties, Toast.LENGTH_SHORT).show();
}
}
public static boolean emailValidation(CharSequence target) {
return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public void startActivity() {
Intent intent = new Intent(getContext(), AccountActivity.class);
intent.putExtra("account", user);
startActivity(intent);
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
#OnClick({R.id.sign_up_email, R.id.btnFbLogin})
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_up_email:
loginEmail();
case R.id.btnFbLogin:
break;
}
}
private void getProfile(Profile profile){
if(profile != null){
ID = profile.getId();
}
}
}
As your facebook login is in Fragment not in activity, so the
callback comes in onActivityResult() of Activity in which this fragment attached.
You can check this after override the onActivityResult() of your activity, and put a debug point there.
After you getting result in your activity onActivityResult() method, you can send it to your fragment's onActivityResult().
Hope this will help.
First of all if you are using LoginButton then you don't need to register with LoginManager. Here is the sample
//Using Facebook's LoginButton
//Register Callback
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email")); //set permissions as public_profile, email, etc
loginButton.setFragment(this); //If you are using in a fragment
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
Now with LoginManager when using Custom Button to login instead of FB's LoginButton
//To check if you are already logged In
boolean loggedIn = AccessToken.getCurrentAccessToken() == null;
// To Manually login. This will launch facebook's login screen.
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("public_profile","email"));
In both the cases, for Fragment or Activity you need to handle onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
I use fragment for facebook login. Normally everything goes fine. But in first time , when user login with facebook s/he redirected to facebook page and give permission to program but then (despite i use CallbackManager.onActivityResult) , program cannot handle the callback and stay background. How can i handle the callback ??
Relative code snippet:
public void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
super.onCreate(savedInstanceState);
callbackManager = CallbackManager.Factory.create();
}
public void onResume() {
Log.i("tago" , "onResume");
super.onResume();
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
tumisim = profile.getName();
firstname = profile.getFirstName();
lastname = profile.getLastName();
sharedtumisimkaydet(tumisim);
sharedfirstnamekaydet(firstname);
sharedlastnamekaydet(lastname);
}
}
public void onStop() {
super.onStop();
getActivity().finish();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.facebookfragment, container, false);
int[] taniticiresimler = {R.mipmap.aciklama,R.mipmap.dene_uc,R.mipmap.yenigus,R.mipmap.galp};
CustomPagerAdapter pagerAdapter = new CustomPagerAdapter(getActivity(),taniticiresimler);
FadingIndicator indicator = (FadingIndicator)view.findViewById(R.id.circleIndicator);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
indicator.setViewPager(viewPager);
indicator.setFillColor(Color.BLUE);
indicator.setStrokeColor(Color.BLACK);
indicator.setRadius(15f);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_friends", "public_profile", "email"));
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
profile = Profile.getCurrentProfile();
if (profile.getId() != null) {
facebookID = profile.getId();
String a = sharedFacebookIDAl();
if (a.equals("defaultfacebookID")) {
sharedilkgiriskaydet(true);
}else if(!a.equals(facebookID)){
sharedilkgiriskaydet(true);
}else{
sharedilkgiriskaydet(false);
}
sharedfacebookIDkaydet(facebookID);
KullaniciProfilCek kPC = new KullaniciProfilCek();
kPC.execute(profile.getId());
}
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
email = object.getString("email");
sharedemailkaydet(email);
cinsiyet = object.getString("gender");
sharedcinsiyetkaydet(cinsiyet);
coverphotourl = object.getJSONObject("cover").getString("source");
sharedcoverphotourlkaydet(coverphotourl);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender,cover");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(getActivity(), "Facebook Login iptal edildi", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getActivity(), "Facebook Login hata oluşturdu", Toast.LENGTH_LONG).show();
}
});
return view;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Log.i("tago" , "geri geldi");
}
Inside the fragment you cannot listen onActivityResult directly. Listen the results in the onActivityResult inside your Activity. Put the code below in the Activity which holds the fragment.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Fragment fragment = (Fragment) getChildFragmentManager().findFragmentByTag(childTag);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, intent);
}
}
and then the OnActivityResult() inside the fragment will work.
You are using onActivityResult() wrong - you do not call super class implementation unless you know you need to. This got nothing with the need of calling super i.e. in onCreate() etc. Here's documentation you should read now:
https://developer.android.com/training/basics/intents/result.html
When I sign in facebook, my callback is not working.
I do not know why this part is not working: loginButton.registerCallback(callbackManager...
This is my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return initView(inflater, container);
}
private View initView(LayoutInflater inflater, ViewGroup container) {
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Log.d("FB","1");
final View view = inflater.inflate(R.layout.fragment_login, container, false);
name=(TextView)view.findViewById(R.id.FBname);
link=(TextView)view.findViewById(R.id.FBlink);
id=(TextView)view.findViewById(R.id.FBid);
LoginButton loginButton = (LoginButton)view.findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
Log.d("FB","access token got.");
//send request and call graph api
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("FB","complete");
Log.d("FB",object.optString("name"));
name.setText("name:" + object.optString("name"));
Log.d("FB", object.optString("link"));
link.setText("link:"+object.optString("link"));
Log.d("FB", object.optString("id"));
id.setText("id:"+object.optString("id"));
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.d("FB", "CANCEL");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.d("FB",exception.toString());
}
});
return view;
}
Thanks for all respondents
did you added this to your activity?
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Here is my fbLoginFragment.java in which I am trying to get the user logged in using Facebook SDK 4.9.0 -:
LoginButton loginButton;
AccessToken accessToken;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fblogin, container, false);
}
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = 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) {
// Application code
String email = object.optString("email");
Log.i("Radhe", response.toString());
Log.i("Radhe", object.toString() + " " +email);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.i("Radhe", "Cancelled");
}
#Override
public void onError(FacebookException e) {
Log.i("Radhe", "Error = " + e);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
Log.i("Radhe", "So Hari it is coming here");
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_birthday");
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void displayMessage(Profile profile) {
/****************************Save user to Parse***********************************/
if (profile != null) {
ParseUser user = new ParseUser();
user.setUsername(profile.getId().toString());
user.setPassword(profile.getId().toString());
user.put("legalname", profile.getFirstName());
user.put("surname", profile.getLastName());
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Radhe", "Radhe! Parse signup is success");
startActivity(new Intent(getActivity().getApplicationContext(), home.class));
} else {
e.printStackTrace();
Log.i("Radhe", "Radhe! Parse signup is failure " + e);
}
}
});
}
}
I have given the permissions also but I am not getting email and date of birth in the JSON object.
Here is the result of my Logcat-:
01-22 16:29:07.909 8841-8841/? I/Radhe: {Response: responseCode: 200, graphObject: {"id":"820969881382796","gender":"male","name":"Pranav Shukla"}, error: null}
01-22 16:29:07.909 8841-8841/? I/Radhe: {"id":"820969881382796","gender":"male","name":"Pranav Shukla"}
You need to add permission as List like below:
....
List<String> permissions = new ArrayList<String>();
permissions.add("public_profile");
permissions.add("email");
permissions.add("user_birthday");
permissions.add("user_friends");
loginButton.setReadPermissions(permissions);
....
Check Facebook doc : public void setReadPermissions(List permissions)