How to fix On error Facebook log in result in android - facebook-login

when I click on the button of sign in the window of choosing facebook profile appears ! but once I confirm the the profile the app crashes . And by using logs I figured out that the register call is not successful so I'have a facebook exeception which causes error , how can i find the source error ?
facebookSignInButton.setOnClickListener(View.OnClickListener {
// Login
Log.i(TAG,"CLICKED")
loginManager.logInWithReadPermissions(this, Arrays.asList("public_profile"))
Log.i(TAG,"Permissions")
loginManager.registerCallback(callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d(TAG, "Facebook token: " + loginResult.accessToken.token)
startActivity(Intent(applicationContext,MainActivity::class.java))
}
override fun onCancel() {
Log.i(TAG, "Facebook onCancel.")
}
override fun onError(error: FacebookException) {
Log.d(TAG, "Facebook onError.")
// This part is written in run console
}
})
})
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
callbackManager!!.onActivityResult(requestCode, resultCode, data)
Log.i(TAG,"RESULT"+resultCode.toString()) // this retrun -1
Log.i(TAG,"REQUEST"+requestCode.toString())
}
I expect starting a new activity while logging.

After printing the msg error the problem is in the hash key it doesn't match any key stored !
so instead if using line cmnds I just use this code in my on create function and then copy the hash key into your facebook developer app
val packageName = this.getApplicationContext().getPackageName()
val info : PackageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
for ( signature in info.signatures) {
var md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
val hashKey = android.util.Base64.encodeToString(md.digest(), 0)
Log.i(TAG,"HADHKEEEY"+hashKey)
}
Log.i(TAG,"NAAAMEE"+packageName)

Related

BillingClient.querySkuDetails(SkuDetailsParams.builder()) not working?

Getting an empty list when fetching with querySkuDetails()?
So in case you've been having this issue lately, where you want to fetch your Google Play Console list of SkuDetail, maybe to show the price of one of the SkuDetail and show it to the user has it was in my case or to display some other information about a SkuDetail from your Google Play Console merchant account. Anyways, here's what's worked for me:
First you need to add this to your build.gradle app file:
implementation "com.android.billingclient:billing-ktx:4.0.0"
Then Inside of my Fragment's ViewModel, I did the following:
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val billingClient by lazy {
BillingClient.newBuilder(application.applicationContext)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build()
}
/**
#param result Returns true if connection was successful, false if otherwise
*/
private inline fun billingStartConnection(crossinline result: (Boolean) -> Unit) {
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
result(true)
}
}
override fun onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
result(false)
}
})
}
sealed class BillingClientObserver {
object Loading : BillingClientObserver()
object ClientDisconnected : BillingClientObserver()
object HasNoPurchases : BillingClientObserver()
object HasNoAdsPrivilege : BillingClientObserver()
object UserCancelledPurchase : BillingClientObserver()
data class UnexpectedError(val debugMessage: String = "") : BillingClientObserver()
}
private val _billingClientObserver: MutableStateFlow<BillingClientObserver> =
MutableStateFlow(BillingClientObserver.Loading)
val billingClientObserver: StateFlow<BillingClientObserver> = _billingClientObserver
suspend fun checkSkuDetailById(productId: String) =
billingStartConnection { billingClientReady ->
if (billingClientReady) {
val skuList = ArrayList<String>()
skuList.add(productId)
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)
viewModelScope.launch(Dispatchers.Main) {
val skuDetailList = withContext(Dispatchers.IO) {
billingClient.querySkuDetails(params.build())
}
skuDetailList.skuDetailsList?.let {
Timber.d("Timber> List<SkuDetails>: $it")
if (it.isNotEmpty()) {
val skuDetails: SkuDetails = it[0]
_goAdsFreePricing.value = skuDetails.price
} else {
_billingClientObserver.value =
BillingClientObserver.UnexpectedError(context.getString(R.string.unable_to_get_price_msg))
}
} ?: run {
_billingClientObserver.value =
BillingClientObserver.UnexpectedError(context.getString(R.string.unable_to_get_price_msg))
}
}
} else {
_billingClientObserver.value =
BillingClientObserver.UnexpectedError(context.getString(R.string.unable_connect_to_play_store))
}
}
}
The most important thing to do for the
BillingClient.querySkuDetails(SkuDetailsParams.builder())
to be successful, is to first establish a successful connection through the
BillingClient.startConnection( listener: BillingClientStateListener)
then do the query on the background thread, very important that the
querySkuDetails()
happens in the background thread as it is made to fail if done on the
#MainThread
then listen for its result on the
#MainThread
like in the above example.

Expo Google Authentication doesn't work on production

I implemented Expo Authentication on my app, following the code from the doc https://docs.expo.io/guides/authentication/#google.
On local with the Expo client its working fine, in the IOS simulator and also in the web browser but when I build the app (expo build android) and try on my Android phone, the Google popup comes, I put my id and it send me back to the login page but NOTHING happen.
I put some alert to understand what was going on but I dont even get any, useEffect doesn't fire, responseGoogle doesnt seem to change.
const [requestGoogle, responseGoogle, promptAsyncGoogle] =
Google.useAuthRequest({
expoClientId:
"my_id",
androidClientId:
"my_id,
webClientId:
"my_id",
});
useEffect(() => {
alert("useEffect fired (Google)");
if (responseGoogle?.type === "success") {
const { authentication } = responseGoogle;
// success
alert("success : "+JSON.stringify(responseGoogle));
// some code to check and log the user...
} else {
alert('no success : '+JSON.stringify(responseGoogle));
}
}, [responseGoogle]);
Any idea ?
Apparently its a know bug so here is not the answer but an alternative with expo-google-sign-in :
import * as GoogleSignIn from "expo-google-sign-in";
async function loginWithGoogle() {
try {
await GoogleSignIn.askForPlayServicesAsync();
const { type, user } = await GoogleSignIn.signInAsync();
if (type === "success") {
alert(JSON.stringify(user));
}
} catch ({ message }) {
toast.show("Erreur:" + message);
alert("login: Error:" + message);
}
}

com.apollographql.apollo.exception.ApolloHttpException: HTTP 500 Internal Server Error

I keep getting the HTTP 500 Internal Server Error in my android studio trying to call a loginQuery with apollo client for android, following this tutorial : link to apollo docs
Yet when I run the same query in graphiQL in my browser, it succeeds.
here's a picture of the error in studio :
here's my code:
String userNumber = numberInput.getText().toString();
String password = passwordInput.getText().toString();
Intent intent;
LogInQuery logInQuery = LogInQuery.builder().nationalID(userNumber).password(password).build();
apolloClient.query(logInQuery).enqueue(new ApolloCall.Callback<LogInQuery.Data>() {
#Override
public void onResponse(#NotNull Response<LogInQuery.Data> response) {
LogInQuery.Data data = response.getData();
List<Error> error = response.getErrors();
assert error != null;
String errorMessage = error.get(0).getMessage();
assert data != null;
Log.d(TAG, "onResponse: " + data.login() + "-" + data.login());
if(data.login() == null){
Log.e("Apollo", "an Error occurred : " + errorMessage);
runOnUiThread(() -> {
// Stuff that updates the UI
loading.setVisibility(View.GONE);
Toast.makeText(LogInActivity.this,
errorMessage, Toast.LENGTH_LONG).show();
});
} else {
runOnUiThread(() -> {
// Stuff that updates the UI
loading.setVisibility(View.GONE);
Toast.makeText(LogInActivity.this,
"New User Created!", Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LogInActivity.this, LogInActivity.class);
//startActivity(intent);
});
}
}
#Override
public void onFailure(#NotNull ApolloException e) {
runOnUiThread(() -> {
Log.e("Apollo", "Error", e);
Toast.makeText(LogInActivity.this,
"An error occurred : " + e.getMessage(), Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
});
}
});
}
I can't find much on the internet to help me solve it. If it's duplicate, direct me to the correct answer.
Check your API in Postman. It's working fine or not! Please share API if possible.

Extracting users friend list from facebook graph api v2.3

I am using facebook SDK 4.0.1. I gave permission for user_friends but I am not able to get friend list of the user. I am getting the count of the user's friends but I want the name of the user's friends and ids
private FacebookCallback<LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
Log.d("Access Token", accessToken.toString());
Profile profile = Profile.getCurrentProfile();
// Log.d("PROFILE","PROFILE IMAHE"+profile.getName());
displayWelcomeMessage(profile);
GraphRequestBatch batch = new GraphRequestBatch(
GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constant.KEY_ID,jsonObject.getString("id"));
editor.putString(Constant.KEY_USER_NAME,jsonObject.getString("name"));
editor.putString(Constant.KEY_USER_FNAME,jsonObject.getString("first_name"));
editor.putString(Constant.KEY_USER_LNAME,jsonObject.getString("last_name"));
// hometown = jsonObject.getJSONObject("hometown");
// editor.putString(Constant.KEY_USER_HOMETOWN,hometown.getString("name"));
editor.putString(Constant.KEY_USER_EMAIL,jsonObject.getString("email"));
editor.putString(Constant.KEY_USER_GENDER,jsonObject.getString("gender"));
// editor.putString(Constant.KEY_USER_DOB,jsonObject.getString("birthday"));
editor.commit();
// town = hometown.getString("name");
// personId = jsonObject.getString("id");
// gen = jsonObject.getString("gender");
// email = jsonObject.getString("email");
Log.d("RESPONCE", "RESPONCE user=" + jsonObject.toString());
Log.d("RESPONCE", "RESPONCE =" + response.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
}),
GraphRequest.newMyFriendsRequest(accessToken, new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray jsonArray, GraphResponse response) {
//Lo Application code for users friends
Log.d("RESPONCE FRIEND", "RESPONCE FRIEND=" + jsonArray.toString());
Log.d("RESPONCE FRIEND", "RESPONCE =" + response.toString());
response.getJSONArray();
}
}));
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch graphRequests) {
// Application code for when the batch finishes
}
});
batch.executeAsync();
Since v2.0 of the Graph API, it is only possible to get friends who authorized your App too - for privacy reasons. More information can be found in this and many other threads about that exact same question: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

Firefox Add-On to redirect urls based on wildcards

I am looking at writing a firefox extension which will take a url, apply a regex to it to produce a second url.
I then need to have firefox redirect to this new URL without the user having to do anyything.
Does anyone have any examples I could use to learn how to do this. I've used the firefox tutorials to get as far as this..
// Import the page-mod API
var pageMod = require("sdk/page-mod");
// Import the self API
var self = require("sdk/self");
// Create a page mod
// It will run a script whenever a ".org" URL is loaded
// The script replaces the page contents with a message
pageMod.PageMod({
include: "*",
contentScript: 'window.alert("Matched Page");'
})
So my question is, how would I do this.
For instance, if a user types in http://www.mywebsite/data/7287232/wherever, I'd like them to be redirected to http://www.anotherwebsite/folder/7287232
Well.. answering to the initial head line:
https://addons.mozilla.org/en-US/firefox/addon/redirector
Or is that actually you? #ScaryAardvark ?
that example is very complex, the main purpose of that traceable channel example is to get a COPY of the sourcecode that gets loaded at that uri.
const { Ci, Cu, Cc, Cr } = require('chrome'); //const {interfaces: Ci, utils: Cu, classes: Cc, results: Cr } = Components;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/devtools/Console.jsm');
var observers = {
'http-on-modify-request': {
observe: function (aSubject, aTopic, aData) {
console.info('http-on-modify-request: aSubject = ' + aSubject + ' | aTopic = ' + aTopic + ' | aData = ' + aData);
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
var requestUrl = httpChannel.URI.spec
if (/\.org/.test(requestUrl) || /http\:\/\/www\.mywebsite\/data\/7287232\/.+/.test(requestUrl)) {
httpChannel.redirectTo(Services.io.newURI('http://www.anotherwebsite/folder/7287232', null, null));
}
},
reg: function () {
Services.obs.addObserver(observers['http-on-modify-request'], 'http-on-modify-request', false);
},
unreg: function () {
Services.obs.removeObserver(observers['http-on-modify-request'], 'http-on-modify-request');
}
}
};
to register the observer on startup of addon run this:
//register all observers
for (var o in observers) {
observers[o].reg();
}
and on shutdown of addon unregister all observers like this:
//unregister all observers
for (var o in observers) {
observers[o].unreg();
}