Can't get location and email using Facebook API - java

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

Related

Facebook reloaded twice in web browser from mobile app

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

java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, ortemprary proof

This Exception is taking place in my code help please. my all code is posted below.
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential
without either verificationProof, sessionInfo, ortemprary proof.
at com.google.android.gms.common.internal.Preconditions.checkArgument(Unknown
Source)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown
Source)
at com.approsoft.momentsapp.providerfrags.EnterPhoneFragment$3.onVerificationCompleted(EnterPhoneFragment.java:177)
at com.google.firebase.auth.api.internal.zzer.zza(Unknown Source)
at com.google.firebase.auth.api.internal.zzeu.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:238)
at android.app.ActivityThread.main(ActivityThread.java:6006)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:937)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:798)
How to resolve this issue before I updated ui version 4.0.1 to 4.2.0 and also update 4.3.1 but not resolve this issue
I have passed too many days on this issue but not resolve please help .
Here is my code
public class EnterPhoneFragment extends Fragment {
Button btnSendCode, btnVerify, btnResendCode;
EditText etCode;
IntlPhoneInput etPhoneNumber;
TextView tvTerms;
PhoneAuthProvider.OnVerificationStateChangedCallbacks verificationCallbacks;
PhoneAuthProvider.ForceResendingToken resendingToken;
FirebaseAuth firebaseAuth;
String phoneVerificationID;
HashMap<String, String> userDetails;
String userID;
private static final long TIMEOUT_DURATION = 60;
SessionManager sessionManager;
FragmentManager fragmentManager;
private MaterialDialog dialogSave;
private String smsCode;
private PhoneAuthCredential credential;
public EnterPhoneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_enter_phone, container, false);
sessionManager = new SessionManager(getActivity());
userDetails = sessionManager.getUserDetails();
userID = userDetails.get(SessionManager.KEY_USER_ID);
fragmentManager = getFragmentManager();
firebaseAuth = FirebaseAuth.getInstance();
setUpVerificationCallbacks();
tvTerms = view.findViewById(R.id.tvTerms);
String termsString = "<u><b>Terms of Service</b></u>";
tvTerms.setText(Html.fromHtml(termsString));
etPhoneNumber = view.findViewById(R.id.etPhoneNumber);
etCode = view.findViewById(R.id.etCode);
etCode.setEnabled(false);
btnResendCode = view.findViewById(R.id.btnResendCode);
btnResendCode.setEnabled(false);
dialogSave = new MaterialDialog.Builder(getActivity())
.title("Sending")
.content("Please wait")
.cancelable(false)
.progress(true, 0).build();
btnVerify = view.findViewById(R.id.btnVerify);
btnVerify.setEnabled(false);
btnVerify.setBackgroundColor(getResources().getColor(R.color.colorGrey));
btnVerify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
if (TextUtils.isEmpty(code)) {
etCode.setError("Enter smsCode first");
etCode.requestFocus();
} else {
if (smsCode.equals(code)) {
signInWithPhoneCredential(credential);
} else {
Toast.makeText(getActivity(), "Enter a valid code!", Toast.LENGTH_SHORT).show();
}
}
}
});
btnSendCode = view.findViewById(R.id.btnSendCode);
btnSendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber;
if (etPhoneNumber.isValid()) {
phoneNumber = etPhoneNumber.getNumber();
verifyPhoneNumber(phoneNumber);
} else {
Toast.makeText(getActivity().getApplicationContext(), "Enter a valid phone number!", Toast.LENGTH_SHORT).show();
}
}
});
saveSetting();
return view;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
public void verifyPhoneNumber(String phoneNumber){
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
getActivity(),
verificationCallbacks);
}
private void setUpVerificationCallbacks() {
try {
verificationCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
//signInWithPhoneCredential(phoneAuthCredential);
smsCode = phoneAuthCredential.getSmsCode();
credential = PhoneAuthProvider.getCredential(phoneVerificationID, smsCode);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid credentials used. Try again!", Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getActivity().getApplicationContext(), "SMS Quota expired. Come back later.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
phoneVerificationID = s;
resendingToken = forceResendingToken;
etPhoneNumber.setEnabled(false);
btnSendCode.setEnabled(false);
etCode.setEnabled(true);
btnVerify.setEnabled(true);
btnVerify.setBackgroundColor(getResources().getColor(R.color.colorIndigoBlue));
btnResendCode.setEnabled(true);
}
};
} catch (Exception ex) {
Log.i("IllegalState", "Exception is Illegal state exception");
}
}
private void signInWithPhoneCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
final String userPhone = user.getPhoneNumber();
RequestQueue queue = Volley.newRequestQueue(getActivity());
try {
dialogSave.show();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.url + "save_phone.php",
new Response.Listener<String>() {
#Override
public void onResponse(String result) {
if (!dialogSave.isCancelled()) {
dialogSave.dismiss();
}
if (result.equals("Error")) {
Toast.makeText(getActivity(), "userId and mobile are not empty!", Toast.LENGTH_SHORT).show();
}
if (result.equals("this mobile number already exist!")) {
Toast.makeText(getActivity(), "this mobile number already exist!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject response = new JSONObject(result);
String userEmail = response.getString("email");
if (userEmail != null && !userEmail.isEmpty()) {
String userID = response.getString("id");
String fbID = response.getString("fb_id");
String googleID = response.getString("google_id");
String firstName = response.getString("first_name");
String lastName = response.getString("last_name");
String userPass = response.getString("password");
String userMobile = response.getString("mobile");
String userLocation = response.getString("location");
String userDOB = response.getString("dob");
String userGender = response.getString("gender");
String posts = response.getString("posts");
String following = response.getString("following");
String followers = response.getString("followers");
String userImagePath = "http://fotogher.com/app/Moments/provider/" + response.getString("image_path");
sessionManager.createLoginSession(userID, userEmail, fbID, googleID,
firstName, lastName, userPass, userMobile, userLocation,
userDOB, userGender, userImagePath, posts, following, followers);
for (int i = 0; i < fragmentManager.getBackStackEntryCount(); i++) {
fragmentManager.popBackStack();
}
startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Profile creation failed. Try again!",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (!dialogSave.isCancelled()) {
dialogSave.dismiss();
}
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mobile", userPhone);
params.put("user_id", userID);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification smsCode entered was invalid
Log.i("Exception","Invalid smsCode entered. Try again!");
}
}
}
});
}
my gradle file is this
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.approsoft.momentsapp"
minSdkVersion 17
targetSdkVersion 27
versionCode 2
versionName "0.1"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
/*implementation 'com.android.support:appcompat-v7:26.1.0'*/
implementation 'com.android.support:design:27.1.1'
/*implementation 'com.android.support.constraint:constraint-layout:1.0.2'*/
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-database:16.1.0'
implementation 'com.google.firebase:firebase-analytics:16.3.0'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.firebase:firebase-messaging:17.4.0'
implementation 'com.google.android.gms:play-services-places:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.firebaseui:firebase-ui-auth:4.2.0'
implementation 'com.facebook.android:facebook-android-sdk:4.29.0'
implementation 'com.github.ittianyu:BottomNavigationViewEx:1.2.4'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.wonderkiln:camerakit:0.13.2'
implementation 'com.camerakit:jpegkit:0.1.0'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'
// compile 'com.github.yalantis:ucrop:2.2.1'
implementation 'com.github.bumptech.glide:glide:4.6.1'
implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
/* implementation 'com.hbb20:ccp:2.2.3'*/
implementation 'com.github.mukeshsolanki:country-picker-android:2.0.1'
implementation 'hani.momanii.supernova_emoji_library:supernova-emoji-library:0.0.2'
//for video view
//implementation 'com.github.halilozercan:BetterVideoPlayer:kotlin-SNAPSHOT'
implementation 'com.android.volley:volley:1.1.1'
//implementation 'com.github.hani-momanii:SuperNova-Emoji:1.1'
//implementation project(':supernova-emoji-library')
// compile 'id.zelory:compressor:2.1.0'
implementation 'net.rimoto:intlphoneinput:1.0.1'
implementation 'com.github.zcweng:switch-button:0.0.3#aar'
implementation 'com.bikomobile:multipart:1.3.4'
implementation 'com.github.shts:StoriesProgressView:3.0.0'
implementation('com.mapbox.mapboxsdk:mapbox-android-sdk:6.5.0#aar') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.19.0'
implementation('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.19.0') {
transitive = true
}
implementation 'com.android.support:multidex:1.0.3'
// testImplementation 'junit:junit:4.12'
// androidTestImplementation 'com.android.support.test:runner:1.0.1'
// androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
apply plugin: 'com.google.gms.google-services'
As Alex Saveau said (one of Firebase UI Developers) :
Users will switch to their messaging app and don't have a lot of RAM available so it kills your app. Since we only store the verification ID in memory, it gets lost. Side note: the number of times we've added bugs like this, you'd think we would learn. Nope. 😂😉
So check your code and memory and trace mabye you can find something to get away from it but for now this problem still not solved
Source : github.com
Add your SHA code on firebase settings to your project. If already done, do the same again with the recent one. It worked for me.

Unable to Make a google Sign In (returns that the user is null)

At the start, sorry if this is the dumbest Question that you have seen. But I have trouble with the Android Google sign in. I am making an application to get the Google sign in.
public class MainActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 1;
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
SignInButton signInButton;
#Override
protected void onStart() {
super.onStart();
isUserSignedIn();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Result return from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed
// no need to attach a listener
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
} else
Log.d("activity", "not done");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void isUserSignedIn() {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account == null) {
promptSignIn();
} else updateUI(account);
}
private void promptSignIn() {
// Configure sign-in to request the user's ID, email address, and basic profile
// ID and basic profile are included in DEFAULT_SIGN_IN
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// Set the dimensions of the sign-in button
signInButton = findViewById(R.id.google_btn);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult();
// Signed in successfully, show authenticated UI
updateUI(account);
} catch (Exception e) {
Log.d("activity", "signInResult:failed code=" + e.getMessage());
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();
Log.d("activity", name);
Log.d("activity", email);
Log.d("activity", photoUrl + "");
Log.d("activity", emailVerified + "");
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
} else
Log.d("activity", "user is null");
}
protected void updateUI(GoogleSignInAccount account) {
if (signInButton != null) signInButton.setVisibility(View.GONE);
}}
Here is the entire code for the activity.
In the method handleSignInResult() I am always gettting a null user.
Here are the gradle files.
Module level>>>
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
compile 'com.google.firebase:firebase-messaging:11.8.0'
compile 'com.google.firebase:firebase-core:11.8.0'
compile 'com.google.firebase:firebase-auth:11.8.0'
compile 'com.google.android.gms:play-services-auth:11.8.0'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'}apply plugin: 'com.google.gms.google-services'
App level>>>>
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files }}allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
The user is null because you never login the user through Firebase. When using Google sign in with Firebase you need to log in the user through both APIs.
Add the following method.
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success
FirebaseUser user = mAuth.getCurrentUser();
} else {
// Sign in failed
}
}
});
}
Add private FirebaseAuth mAuth;
Add mAuth = FirebaseAuth.getInstance(); to onCreate()
Call firebaseAuthWithGoogle() when the Google login is successful in your handleSignInResult().
In my case i am getting same error like "NULL USER"...
But, the silly mistake made by me was...
I forgot to initialize private FirebaseAuth mAuth;
once i initialized variable like below problem solved...
mAuth = FirebaseAuth.getInstance();
Note: Add mAuth = FirebaseAuth.getInstance(); to onCreate()

Facebook API doesn't return email

I know that this question has been asked, but there is only one answer pretty much or is not even answered.
I dont know if it's my lack of understanding or lack of Facebook documentation, but so far i have this code to retrieve user email.
callbackManager = CallbackManager.Factory.create();
mFbLoginManager.registerCallback(
callbackManager,
new FacebookCallback < LoginResult > () {
#Override
public void onSuccess(final LoginResult loginResult) {
// Handle success
Log.i(TAG, "callBack Login Result: LoginManager success - " + loginResult.toString());
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject userObject, GraphResponse response) {
if (response.getError() == null) {
try {
AccessToken token = AccessToken.getCurrentAccessToken();
Log.e(TAG, token.getToken());
Log.e(TAG, userObject.toString());
email = userObject.getString("email");
} catch (JSONException ex) {
Log.e(TAG, "Not such permissions for email!");
ex.printStackTrace();
}
Log.d(TAG, "Email fetched: " + email);
}else{
Log.e(TAG, "Something went wrong with fetching email with GraphRequest");
}
}
}).executeAsync();
}
The JSON string returns only the name and the id, therefore my email variable is empty.
The part i am troubled with is that when i test it on Graph Explorer or with that link, i get the email.
I have se permissions also on the developers site dashboard and also in my code(that's inside onClick() when user press the facebook login button):
mFbLoginManager.logInWithReadPermissions(LoginActivity.this, Arrays.asList("user_photos", "email", "public_profile")
So i am not sure what is the problem in my code. The login button is custom and not the facebook LoginButton, i dont know if that matters.
Every help is welcome
Add below depandancy in Gradle
implementation 'com.facebook.android:facebook-android-sdk:4.11.0'
enter code here
FacebookSdk.sdkInitialize(this);
callbackManager =CallbackManager.Factory.create();
// -----start putting in oncreate-----------------------
LoginManager.getInstance().logInWithReadPermissions(UserActivity.this, Arrays.asList("public_profile", "user_friends","email"));
facebookTime();
//----onclicklisterner ---------------/
callbackManager.onActivityResult(requestCode,resultCode,data);
//---onactivityresult-------------/
public void facebookTime() {
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Util.showCenteredToast(getActivity(), "object" + object);
// Util.showCenteredToast(getActivity(), "GraphResponse" + response);
try {
strEmail = object.getString("email");
strUserName = object.getString("name");
String id = object.getString("id");
// write your code here
//asyncTask.iSocialMediaResponse = LoginFragment.this;
asyncTask.execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name");
//parameters.putString("fields", "user_friends");
request.setParameters(parameters);
//Log.e(" About to Graph Call", " ");
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Util.showCenteredToast(UserActivity.this, "oncancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Util.showCenteredToast(UserActivity.this, "exception" + exception);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}

Facebook - Post to wall

I have this code.. The only working here is the Login... I want to achieve the Publish to wall or feed dialog.. I have here the code for the wall post but It still not working.. Any help will be appreciated... I followed this link for my Login
[a link] http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
I am trying to embed the post status in this Login..
public class FacebookActivity extends FragmentActivity {
private Button publishButton;
private String TAG = "FacebookActivity";
private TextView lblEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_activity);
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new OnErrorListener(){
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
// TODO Auto-generated method stub
});
// set permission list, Don't forget to add email
authButton.setReadPermissions(Arrays.asList("basic_info","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG,"Access Token"+ session.getAccessToken());
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,Response response) {
if (user != null) {
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
lblEmail.setText(user.asMap().get("email").toString());
}
}
});
publishButton.setVisibility(View.VISIBLE);
}
else if (state.isClosed()) {
publishButton.setVisibility(View.INVISIBLE);
}
}
});
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishFeedDialog();
}
});
}
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity().getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
protected ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

Categories