Facebook reloaded twice in web browser from mobile app - java

While Clicking on facebook button,redirect to web browser and open facebook login page.After enter our credentials and need to click the CONTINUE Button, On first click of Continue button, facebook page reloaded and second time it fetched all User details (Email,first Name,Last Name,Profile pic) on Android 9 OS only..Android 10,11 12 OS devices working.
We have used android:launchmode as SINGLETASK for android 10,11 & 12.but Android 9 OS not supporting.
Library : implementation 'com.facebook.android:facebook-android-sdk:14.1.1'
Android Manifest:
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider399122648326004"
android:exported="true"
tools:ignore="ExportedContentProvider" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<meta-data
android:name="com.facebook.sdk.ClientToken"
android:value="#string/facebook_client_token" />
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:launchMode="singleTask"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
tools:replace="android:theme" />
In Android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeUtils.changeTheme(this);
setContentView(R.layout.activity);
FacebookSdk.sdkInitialize(ApprovalInHours.this);
callbackManager = CallbackManager.Factory.create();
facebookLogin();
});
Here We have written code for loginbutton and asking ReadPermissions
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginManager.logInWithReadPermissions(ApprovalInHours.this, Arrays.asList(
"email",
"public_profile",
"user_birthday"));
}
});
Code for facebookLogin() and fetching user facebook details:
private void facebookLogin() {
LoginManager.getInstance().registerCallback(callbackManager,new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("onSuccess",""+loginResult.toString());
//Use GraphApi to get the information into the app.
GraphRequest request = GraphRequest.newMeRequest(
//pass two parameter
loginResult.getAccessToken(), //one is the current token
new GraphRequest.GraphJSONObjectCallback() //2nd is grahJSONObject callback
{
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("MainActivity", response.toString() + "getToken" + AccessToken.getCurrentAccessToken());
// Application code
try {
String obj = object.toString(); //get complete JSON object refrence.
String name = object.getString("first_name"); //get particular JSON Object
String last_name = object.getString("last_name");
final_name = name + last_name;
Log.d("checkFinalName", "" + final_name);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
parameters.putString(
"fields",
"id, first_name, last_name, name, picture, email,gender"
);
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("onCancel","onCancel");
}
#Override
public void onError(FacebookException exception) {
Log.d("onError","onCancel"+exception.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == -1){
LoginManager.getInstance().logOut();
}
Log.d("checkLog",""+"checkLog");
}

Related

how to log in with my twitter account in an android application with twiterkit

I am making an android application using java as the programming language. The app in its main window has 3 buttons to be able to log in with the account of any of its social networks (facebook, twitter and gmail respectively),I implemented this in a new activity. I was developing the button to be able to log in with my twitter account using twitter kit but when I click I get the message = "Login fail" and it does not take into consideration the previous code. I hope you can help me. Greetings
my code:
public class loggin extends AppCompatActivity {
//variable twitter
TwitterLoginButton login;
//other variables
TextView recoveruser,recoverpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Twitter.initialize(this);
login = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
//configuraciĆ³n para twitter:
login.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
TwitterSession session =TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
if (token != null ) {
//Log.d(TAG, "twitter token" + token);
Toast.makeText(getApplicationContext(),"twitter token" + token,Toast.LENGTH_LONG).show();
}
if (secret != null ) {
Toast.makeText(getApplicationContext(), "twitter secret" + secret,Toast.LENGTH_LONG).show();
// Log.d(TAG, "twitter secret" + secret);
}
String userName=session.getUserName();
Intent intent= new Intent(loggin.this,MainActivity.class);
intent.putExtra("username",userName);
startActivity(intent);
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),"Login fail",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
login.onActivityResult(requestCode, resultCode, data);
}
}

Why can't I implement Google places API?

I am trying to implement the Place Picker API by Google. But every time I start the activity, it just closes instantly.
Code for implementing Place Picker:
int PLACE_PICKER_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up_2);
btn3 = (Button) findViewById(R.id.button2);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = getApplicationContext();
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
The API key has been declared in my manifest file:
<manifest>
<application
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_place_api" />
</application>
</manifest>
Logcat error:
BasicNetwork.performRequest: Unexpected response code 403 for https://www.googleapis.com/placesandroid/v1/search?key=AIzaSyCHWpRWCGo_YUKwzHn4Qv6yP5q9E5TNRJA
2019-04-28 07:49:21.729 2875-5225/? E/Places: Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.
Why does this error occur even though Google places is enabled on my account?
Note: I have also set up my billing account.
Places API for Android does not seem to be enabled for your app: double check it
private void openAutocompleteActivity(int req) {
try {
PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
// .build(this);
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
startActivityForResult(builder.build(this), req);
// PlacePicker.IntentBuilder builder1= new PlacePicker().IntentBuilder();
// startActivity(builder1.build(this), 112);
// startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException e) {
GoogleApiAvailability.getInstance().getErrorDialog(this,
e.getConnectionStatusCode(),
0 /* requestCode */).show();
} catch (GooglePlayServicesNotAvailableException e) {
String message = "Google Play Services is not available: " +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
// Log.e(TAG, message);
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
/**
* Called after the autocomplete activity has finished to return its result.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that the result was from the autocomplete widget.
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
LatLng xyzlatlng= place.getLatLng();
double lat=xyzlatlng.latitude;
double lon=xyzlatlng.longitude;
}
}

Check whether a user used facebook sdk to login into app previously

Currently I have a code where I have a facebook login button in my login page. And right now I'm trying to make a check first whether a user already logged in into my app using facebook when the facebook login button is clicked. I read the facebook documentation here on how to do it but I have no idea where to apply this in my code.
loginbutton
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions(Arrays.asList("email","public_profile"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("LoginResult : ", loginResult.getAccessToken().getToken());
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
try{
// Application code
String email = object.getString("email");
String firstName = object.getString("first_name");
String lastName = object.getString("last_name");
ArrayList<String> publicProfile = new ArrayList<String>();
publicProfile.add(email);
publicProfile.add(firstName);
publicProfile.add(lastName);
new RegisterGetList(LoginActivity.this,mProgressView,LoginActivity.this, publicProfile).execute();
}
catch (JSONException e1){
e1.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email");
request.setParameters(parameters);
request.executeAsync();
}
We will get Facebook user account id,So from the backend you have to check whether that userId is already registered or not.Then you can solve the issue.
You can store the email in shared preferences and you can check if shared preferences is null or not.
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(context);
String email=sp.getString("email",null);
if(email==null)
{
//first log in
//store the email in shared prefernces
SharedPreferences.Editor editor = sharedPreferences.edit()
editor.putString("email",value);
editor.apply();
}
else
{
//already logged in
}
clear the sp when user wil logout.
Check this in your onCreate that user is logged in or not.
if (AccessToken.getCurrentAccessToken() != null) {
getUserDetails();
} else{
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
}
and getting user details using :
private void getUserDetails() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
Log.i(TAG, "Response >>: " + object.toString());
String userID = object.getString("id");
String strName = object.getString("name").toString();
String strgander = object.getString("gender").toString();
String strEmail = object.getString("email").toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,link,gender,age_range,cover,picture,location");
request.setParameters(parameters);
request.executeAsync();
}
set permission in Login button's onClick.
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
}
});
set callback to Login button using
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
And, finally just call "getUserDetails()" inside onSuccess callback of your login button.

Can't get passed Google Drive "Choose Account" screen in Android

I'm trying to incorporate the Google Drive API within my android application.
I have added google play services to my build.gradle along with getting the Android API key. My issue is within the OnResume() where the user picks the account.
It just keeps reprompting the user to choose account and does not proceed.
May anyone help me ?
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private static final String TAG = "Google Drive Activity";
private static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
private boolean fileOperation = false;
private DriveId mFileId;
public DriveFile file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient != null) {
// disconnect Google API client connection
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
public void onClickCreateFile(View view){
fileOperation = true;
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
public void onClickOpenFile(View view){
fileOperation = false;
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
public void OpenFileFromGoogleDrive(){
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[] { "text/plain", "text/html" })
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (result.getStatus().isSuccess()) {
if (fileOperation == true) {
CreateFileOnGoogleDrive(result);
} else {
OpenFileFromGoogleDrive();
}
}
}
};
public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result){
final DriveContents driveContents = result.getDriveContents();
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("Hello abhay!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("abhaytest2")
.setMimeType("text/plain")
.setStarred(true).build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (result.getStatus().isSuccess()) {
Toast.makeText(getApplicationContext(), "file created: "+""+
result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
}
return;
}
};
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + "");
String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
}
This is my manifest. Blocking the API Key.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.moli9479csumb.version1googledrive">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyD_2eJ5pPdRMysVwxxxxxxxxxxxxxx"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You get the AccountSelector when the GoogleApiClient is not able to connect and has a resolution which requires the user to authorize the App for the API. This happens when you call "result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);" from the onConnectionFailed method.
Once the user selects the account your activity gets a callback with the code REQUEST_CODE_RESOLUTION. This code must be handled and you should call apiClient.connect() to connect again when this code is received in onActivityResult method.
See this for more details. I hope it works :)
You can easily force to prompt the user to choose account by using [Account Picker](https://developer.android.com/reference/android/accounts/AccountManager.html#newChooseAccountIntent(android.accounts.Account, java.util.ArrayList, java.lang.String[], boolean, java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle)), common account picker is similar to the standard framework account picker introduced in newChooseAccountIntent. Returns an intent to an Activity that prompts the user to choose from a list of accounts. The caller will then typically start the activity by calling startActivityForResult(intent, ...);.
On success the activity returns a Bundle with the account name and type specified using keys KEY_ACCOUNT_NAME and KEY_ACCOUNT_TYPE.
The most common case is to call this with one account type, e.g.:
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, SOME_REQUEST_CODE);
The account picker activity will return when the user has selected and/or created an account, and the resulting account name can be retrieved as follows:
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == SOME_REQUEST_CODE && resultCode == RESULT_OK) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
}
}
Here's the Official Google Sample code which uses the above code with concrete explanation how to use API: https://developers.google.com/drive/v3/web/quickstart/android#step_5_setup_the_sample
Take a look at your onResume() and onConnectionFailded() methods.
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
What happens?
In onResume() you create GoogleApiClient and call connect(). Connection fails because you are not authorized with an account. Method onConnectionFailed() is executed which opens a resolution which is actually another activity called for result. You choose an acount but I guess authorization fails or is cancelled.
You return to your original activity and onResume() is executed. And you go a full circle again.
Why does your authorization fail? I guess because there is something wrong with your credentials. Go to Developer console and create O Auth credentials for your package and your key signature.

Can't get location and email using Facebook API

In my Android application I developed this code to login with my account and get user property like name, location and email. The problem is I can get the name, but I can't get the email and the location. When I tried my code without try catch the application crush and my log point in getproperty("email") and getlocation(). When I use the try. The application work but there is no email or location.
public class Share extends Fragment {private static final String TAG ="Share";private UiLifecycleHelper uiHelper;
private View otherView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To maintain FB Login session
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.share, container, false);
// Looks for Login button
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
// Set View that should be visible after log-in invisible initially
otherView = view.findViewById(R.id.other_views);
otherView.setVisibility(View.GONE);
//authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));
return view;
}
// Called when session changes
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,Exception exception) {
onSessionStateChange(session, state, exception);
}
};
// When session is changed, this method is called from callback method
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
final TextView name = (TextView) getView().findViewById(R.id.name);
final TextView mail = (TextView) getView().findViewById(R.id.mail);
final TextView location = (TextView) getView().findViewById(R.id.location);
final TextView locale = (TextView) getView().findViewById(R.id.locale);
final TextView info = (TextView)getView().findViewById(R.id.msginfo);
final LinearLayout views= (LinearLayout)getView().findViewById(R.id.other_views);
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
// make request to the /me API to get Graph user
views.setVisibility(View.VISIBLE);
info.setText("You can now share images in facebook ");
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
// Set view visibility to true
otherView.setVisibility(View.VISIBLE);
// Set User name
name.setText("Hello " + user.getName());
// Set Email
mail.setText("Your Email: " + user.getProperty("email").toString());
locale.setText("Locale: " + user.getProperty("locale").toString());
location.setText("Your Current Location: " + user.getLocation().getProperty("name").toString());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
} else if (state.isClosed()) {
views.setVisibility(View.INVISIBLE);
info.setText("If you want to share images in Facebook, please Login");
Log.i(TAG, "Logged out...");
otherView.setVisibility(View.GONE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "OnActivityResult...");
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
The issue is that you have not asked for permissions:
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));
However, you are using an older Facebook SDK, while the newest SDK is 4.0.+. Below, I will give you a full sample code for Facebook login, based on the newest API. Keep in mind that you first have to add your application in developers.facebook as the documentation mentions out.
public class LoginActivity extends ActionBarActivity{
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.loginFaceBook_button);
List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
System.out.println("onSuccess");
GraphRequest request = GraphRequest.newMeRequest
(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject object, GraphResponse response)
{
// Application code
Log.v("LoginActivity", response.toString());
//System.out.println("Check: " + response.toString());
try
{
String id = object.getString("id");
String name = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
System.out.println(id + ", " + name + ", " + email + ", " + gender + ", " + 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());
}
});
}
}
If you want to use Fragment instead of ActionBarActivity, the just add loginButton.setFragment(this); right after your permission line.
manifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
<!-- your other attrs..-->
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id"/> <!-- Get this one from developers.facebook -->
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name"/>
You will need to add to your application a hash key too. Here is a way to do this with code:
try
{
//paste Your package name at the first parameter
PackageInfo info = getPackageManager().getPackageInfo("PUT_YOUR_PACKAGE_NAME_HERE",
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String sign = Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.e("MY KEY HASH:", sign);
Toast.makeText(getApplicationContext(),sign, Toast.LENGTH_LONG).show();
}
}
catch (PackageManager.NameNotFoundException e)
{
}
catch (NoSuchAlgorithmException e)
{
}
After it prints you out the hash key, you copy paste it to your facebook.developer account, where your project is located.
In grandle, you should add jcenter in repositories and also add compile 'com.facebook.android:facebook-android-sdk:4.0.0' in dependecies.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects
{
repositories {
jcenter()
/*more project attrs..*/
}
}
And the other grandle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "YOUR_PACKAGE_NAME"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
Edit:
In order to track the user's location, you will need a GPS Tracker, something like this. "user_location" permission does not return a lon, lat, but a Page object, which I think is not what you want. So, your permissions should be List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile"); and now you should be able to retrieve user's email

Categories