Parse and Facebook SDK accessToken return null - facebook

I'm trying to extract information using the Facebook Graph Api along with Parse API. When calling the Graph API, The GraphRepsone is null. The problem is because the accessToken is null but I can't figure out how to fix after trying many different ways.
buttonSignUpWithFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// this is where you can begin doing facebook sign up process
Log.i(TAG, "did click on facebook button");
List<String> permissions = Arrays.asList("user_location", "user_friends", "email", "public_profile");
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpActivity.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("App", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("App", "User signed up and logged in through Facebook!");
startActivity(new Intent(SignUpActivity.this, Home.class));
} else {
Log.d("App", "User logged in through Facebook!");
setupUser();
startActivity(new Intent(SignUpActivity.this, Home.class));
}
}
public void setupUser() {
accessToken = AccessToken.getCurrentAccessToken();
}
});
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (response != null) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
Log.d(TAG, "first name " + firstName);
} catch (JSONException e) {
e.printStackTrace();
}
// String firstName = jsonResponseObject.getFirstName();
// String lastName = jsonResponseObject.getLastName();
}
}
});
Bundle param = new Bundle();
param.putString("fields","cover, birthday, email, first_name, last_name, ");
request.setParameters(param);
request.executeAsync();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}

I'd hate to give a vague answer, but I don't think the problem is in the code snippet. I suggest you revise your steps and make sure you followed these links completely again:
https://developers.facebook.com/docs/android/getting-started
https://parse.com/docs/android/guide#users-facebook-users

Related

following facebook login: setReadPermissions and registerCallback giving me error

trying to use FB login, followed their steps, but Android Studio gives me error: Cannot resolve methods .setReadPermissions and .registerCallback...
am new to this development and tech world... please, help! What am I doing wrong? Looked through many Q&A here, but none is giving me answers. Help much appreciated. Thanks!
I am trying to build a simple OCR app, with FB, Google logins and one independent register button. Code for registration class as follows:
public class Registration extends AppCompatActivity {
DatabaseHelper databaseHelper;
CallbackManager callbackManager;
GoogleSignInClient mGoogleSignInClient;
private static final String TAG = "AndroidClarified";
EditText et_username, et_password, et_cpassword, et_email;
RadioGroup radioSexGroup;
RadioButton radioSexButton;
Button btn_register, btnFBLogin, google_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
try {
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
AccessToken accessToken = AccessToken.getCurrentAccessToken();
Profile profile = Profile.getCurrentProfile();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
google_button = findViewById(R.id.google_button);
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getResources().getString(R.string.web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
et_username = findViewById(R.id.et_username);
et_password = findViewById(R.id.et_password);
et_cpassword = findViewById(R.id.et_cpassword);
et_email = findViewById(R.id.et_email);
radioSexGroup = findViewById(R.id.radioGroup);
final int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = findViewById(selectedId);
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = et_username.getText().toString();
String password = et_password.getText().toString();
String confirm_password = et_cpassword.getText().toString();
String email = et_email.getText().toString();
if (username.equals("") || password.equals("") ||
confirm_password.equals("") || email.isEmpty()) {
Toast.makeText(getApplicationContext(), "Fields Required",
Toast.LENGTH_SHORT).show();
} else {
if (password.equals(confirm_password)) {
boolean checkUsername =
databaseHelper.CheckUsername(username);
if (checkUsername) {
boolean insert = databaseHelper.Insert(username,
password, email);
if (insert) {
Toast.makeText(getApplicationContext(),
"Registered", Toast.LENGTH_SHORT).show();
et_username.setText("");
et_password.setText("");
et_cpassword.setText("");
et_email.setText("");
}
if (!isValidEmail(et_email.getText().toString())) { Toast.makeText(getApplicationContext(), "Email is not valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Username already taken", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_SHORT).show();
}
}
}
}
private boolean isValidEmail(String email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
});
callbackManager = CallbackManager.Factory.create();
btnFBLogin = findViewById(R.id.btnFBLogin);
List permissionNeeds = Arrays.asList("email", "user_birthday", "gender");
btnFBLogin.performClick();
btnFBLogin.setReadPermissions(permissionNeeds);
btnFBLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
if (AccessToken.getCurrentAccessToken() != null) {
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");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
#Override
public void onCancel() {
Log.d("fb_login_sdk", "callback cancel");
}
#Override
public void onError(FacebookException exception) {
Log.d("fb_login_sdk", "callback onError");
}
});
google_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 101);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
switch (requestCode) {
case 101:
try {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
GoogleSignInAccount account = task.getResult(ApiException.class);
String idToken = account.getIdToken();
onLoggedIn(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
break;
}
}
private void onLoggedIn(GoogleSignInAccount mGoogleSignInAccount) {
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra(ProfileActivity.GOOGLE_ACCOUNT, mGoogleSignInAccount);
startActivity(intent);
finish();
}
public void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (GoogleSignIn.getLastSignedInAccount(this) != null) {
Toast.makeText(this, "Already Logged In", Toast.LENGTH_SHORT).show();
onLoggedIn(account);
} else {
Log.d(TAG, "Not logged in");
}
}
}

Android app facebook login integration to display username, email id and profile photo

In Android app I have integrated Facebook login in android studio. I want to display username, user email id and a user profile photo after login. How will I get it?
Use this for user information. Its work successfully.
loginButton = (LoginButton) findViewById(R.id.login_button);
List < String > permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity", response.toString());
try {
id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
name = object.getString("name");
email = object.getString("email");
gender = object.getString("gender");
birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent data) {
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}

I am working with facebook game request

I finished working with sending the request with android reading https://developers.facebook.com/docs/howtos/androidsdk/3.0/send-requests/
but i'm having a problem with handling requests.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/app-link-requests/
I think I did what it told me to do, but I can't get the uri and the requestid
they are all null.
I thing the problem is that when I receive a request I can't click the accept button.
It says that the playstore can't find the app. So the request doesn't disappear.
How can I solve the problem?
public class MainActivity extends Activity {
private static final List<String> PERMISSIONS = Arrays
.asList("read_requests");
private Bundle SIS;
private Session.StatusCallback logincallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
updateview();
getp();
loginlogoutbutton.setText("Login");
onSessionStateChange(session, state, exception);
} else {
}
}
};
public void updateview() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
tt.setText(user.getId());
}
}
});
} else
{
tt.setText("Login");
}
}
private Button loginlogoutbutton;
private Button sendrequestbutton;
private Button testbtn;
private TextView tt;
private String app_id = "APP ID";
private String requestId;
public void getp() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS)
.setCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
}
}));
} else {
}
}
#Override
public void onResume() {
super.onResume();
checkforrequest();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SIS = savedInstanceState;
tt = (TextView) findViewById(R.id.tex);
loginlogoutbutton = (Button) findViewById(R.id.loginlogoutbtn);
loginlogoutbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLoginLogout();
}
});
sendrequestbutton = (Button) findViewById(R.id.sendrequest);
sendrequestbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendRequestDialog();
}
});
testbtn = (Button) findViewById(R.id.button1);
testbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
checkforrequest();
}
});
ConfirmLogin(app_id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public boolean ConfirmLogin(String iappid) {
app_id = iappid;
Session session = Session.getActiveSession();
boolean dd = true;
if (session == null) {
if (SIS != null) {
session = Session.restoreSession(this, null,
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
// TODO Auto-generated method stub
}
}, SIS);
}
if (session == null) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
dd = true;
} else {
dd = false;
}
}
return dd;
}
public void onClickLoginLogout() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else if (session.isClosed()) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else {
session.closeAndClearTokenInformation();
loginlogoutbutton.setText("Login");
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message",
"Learn how to make your Android apps social");
params.putString("data", "{\"badge_of_awesomeness\":\"1\","
+ "\"social_karma\":\"5\"}");
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
} else {
}
} else {
final String requestId = values
.getString("request");
if (requestId != null) {
maketoast(requestId);
} else {
}
}
}
}).build();
requestsDialog.show();
}
public void checkforrequest() {
maketoast("0");
Uri intentUri = this.getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
maketoast("1 : " +requestIdParam);
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
}
}
else
{
maketoast("uri = null");
}
}
public void maketoast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
maketoast("2");
Request request = new Request(Session.getActiveSession(), inRequestId,
null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the
// key/value info
JSONObject dataObject = new JSONObject(
(String) graphObject
.getProperty("data"));
// Get the value for the key -
// badge_of_awesomeness
String badge = dataObject
.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma = dataObject
.getString("social_karma");
// Get the sender's name
JSONObject fromObject = (JSONObject) graphObject
.getProperty("from");
String sender = fromObject
.getString("name");
String title = sender + " sent you a gift";
// Create the text for the alert based on
// the sender
// and the data
message = title + "\n\n" + "Badge: "
+ badge + " Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
maketoast(message);
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// Check if the user is authenticated and
// an incoming notification needs handling
if (state.isOpened() && requestId != null) {
maketoast("3");
getRequestData(requestId);
requestId = null;
} else if (requestId == null) {
maketoast("4");
}
if (state.isOpened()) {
} else if (state.isClosed()) {
}
}
}
this is the code.

How to Post an Image on Facebook Friend's Wall using Android

I have developed an App in which i am allowing user to post an Image on Friends wall, here i have given only single Static Image, by using below code.
params.putString("picture", FacebookUtility.HACK_ICON_URL);
where HACK_ICON_URL,
It is the URL of an Image...
But now i want to let users to select an image from multiple images and then post on Friends Wall.
FriendsList.java:
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
try {
final long friendId;
friendId = jsonArray.getJSONObject(position).getLong("uid");
String name = jsonArray.getJSONObject(position).getString("name");
new AlertDialog.Builder(this)
.setTitle(R.string.post_on_wall_title)
.setMessage(
String.format(getString(R.string.post_on_wall),
name))
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Bundle params = new Bundle();
params.putString("to",
String.valueOf(friendId));
params.putString("caption",
getString(R.string.app_name));
params.putString("description",
getString(R.string.app_desc));
params.putString("link", "http://www.google.com");
params.putString("picture",
FacebookUtility.HACK_ICON_URL);
params.putString("name",
getString(R.string.app_action));
FacebookUtility.facebook
.dialog(FriendsList.this,
"feed",
params,
(DialogListener) new PostDialogListener());
}
}).setNegativeButton(R.string.no, null).show();
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}

Integrating Facebook into my Android app

I searched a lot for a perfect example of code that helps me understand how to integrate Facebook in my application. How can I integrate it?
please do the steps give in the below link
facebook android integration
You could use: http://code.google.com/p/facebook4j/
private static final String FB_KEY = "YOUR_KEY";
private Facebook facebook;
private String messageToPost;
facebook = new Facebook(FB_KEY);
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
public void loginAndPostToWall() {
facebook.authorize(activity, FB_PERMISSIONS,
Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
public void postToWall(String message) {
FBThread fbPost = new FBThread (message);
fbPost.start();
}
private class FBThread extends Thread {
String message;
FBThread(String message) {
this.message = message;
}
#Override
public void run() {
Bundle parameters = new Bundle();
parameters.putString("message", message);
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters,
"POST");
if (response == null || response.equals("")
|| response.equals("false")) {
toastMessage = "Blank response.";
} else if (response.contains("error")) {
toastMessage = "Post Failed because of duplicates...";
} else {
toastMessage = "Message posted to your facebook wall!";
}
} catch (Exception e) {
toastMessage = "Failed to post to wall!";
e.printStackTrace();
}
}
}
class LoginDialogListener implements DialogListener {
public void onCancel() {
android.webkit.CookieManager.getInstance().removeAllCookie();
}
public void onComplete(Bundle values) {
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onError(DialogError error) {
android.webkit.CookieManager.getInstance().removeAllCookie();
}
public void onFacebookError(FacebookError error) {
android.webkit.CookieManager.getInstance().removeAllCookie();
}
}