Facebook SDK Graphrequest returns null - java

Using Facebook SDK 4.4 in Xamarin.Android project. I have the following method :
protected override void OnCreate(Bundle savedInstanceState)
{
LoginButton button = FindViewById<LoginButton>(Resource.Id.FbLoginBtn);
button.SetReadPermissions(new List<string>{ "public_profile", "email" });
mCallBackManager = CallbackManagerFactory.Create();
button.RegisterCallback(mCallBackManager, this);
button.Click += (o, e)=>
{
GraphRequest request = GraphRequest.NewMeRequest(AccessToken.CurrentAccessToken, this);
Bundle paramenters = new Bundle();
paramenters.PutString("fields", "id,name,email,first_name,last_name");
request.Parameters = paramenters;
request.ExecuteAsync();
};
}
public void OnCompleted(JSONObject #object, GraphResponse response)
{
if (#object != null)
{
userEmail.Text = #object.ToString();
}
}
The problem with the above code is that, in the OnCompleted method, the JSONObject always return null when i log in to my facebook account from the app. But when i click the button again to Log Out, i get the proper json with all fields that i specified.
My question is, why is the GraphRequest returning null upon log-in but successfully returns the JSON upon log out?

Related

How to update the Flutter app state after navigating back from Android Java activity?

From the Flutter side, using the PlatformChannel, I am navigating to an Android Java activity, and doing some processes.
The activity successfully opens and I'm able to do the functionality and have the final result of it.
How may I navigate back to the Flutter side to a specific page and pass a value?
P.S.: without going back to the same page and then redirecting to the
next page.
On the Flutter side:
I have these variables
/// Filters Method Channel
final filtersChannel = const MethodChannel('flutter.native/filters');
/// Filters Method Channel
final filtersResultChannel = const MethodChannel("flutter.native/result_filters");
I have a floatingActionButton with this function which invokes a MethodChannel
Future<void> startNewActivity() async {
try {
await filtersChannel.invokeMethod('open_filters');
} on PlatformException catch (e) {
debugPrint("Failed to Invoke: '${e.message}'.");
}
}
On the MainActivity.java
On the protected void onCreate(#Nullable Bundle savedInstanceState) function, I'm starting an activity which has the AR video recording like this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, FiltersActivity.class);
startActivity(intent);
}
On the FiltersActivity.java
On the public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) function
I’m defining and invoking my two channels:
The flutter.native/result_filters channel which builds the UI and
the functionality.
The flutter.native/filters channel which returns the final result.
Here:
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
String resultFiltersChannelIdentifier = "flutter.native/result_filters";
filtersResultChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), resultFiltersChannelIdentifier);
String filtersChannelIdentifier = "flutter.native/filters";
MethodChannel filtersChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), filtersChannelIdentifier);
filtersChannel.setMethodCallHandler(this::filtersMethodCallHandler);
}
Then, the flutter.native/filters displays the UI using the filtersMethodCallHandler function. Here:
private void filtersMethodCallHandler(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("open_filters")) {
openUI();
} else {
result.notImplemented();
}
}
In the openUI function, I'm assigning the record button a function, here:
recordButton.setOnClickListener(this::toggleRecording);
And here's the toggleRecording function:
public void toggleRecording(View unusedView) {
boolean recording = videoRecorder.onToggleRecord();
if (recording) {
recordButton.setImageResource(R.drawable.round_stop);
Toast.makeText(this, "Started Recording", Toast.LENGTH_SHORT).show();
} else {
recordButton.setImageResource(R.drawable.round_videocam);
Toast.makeText(this, "Recording Stopped", Toast.LENGTH_SHORT).show();
videoPath = videoRecorder.getVideoPath().getAbsolutePath();
Toast.makeText(this, "Video saved: " + videoPath, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Video saved: " + videoPath);
// Send notification of updated content.
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.TITLE, "Sceneform Video");
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.Video.Media.DATA, videoPath);
getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
filtersResultChannel.invokeMethod("filters_result", videoPath);
finish();
}
}
As shown above, I'm invoking the filters_result method for the filtersResultChannel channel and I'm adding the videoPath to it.
And then, I'm calling the finish(); method to close the FiltersActivity and return back to the MainAvtivity which successfully returns me to the Flutter page!
BACK to the Flutter side,
I'm listening to the filtersResultChannel like this:
#override
void initState() {
super.initState();
filtersResultChannel.setMethodCallHandler(_filtersResultHandler);
}
Future _filtersResultHandler(MethodCall methodCall) async {
if (methodCall.method == "filters_result") {
final videoPath = methodCall.arguments;
if (videoPath != null && videoPath.length >= 0) {
SchedulerBinding.instance.addPostFrameCallback((_) {
debugPrint("YES YES YES => $videoPath");
setState(() {
reportStatus = videoPath;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoShow(clipPath: videoPath),
),
);
});
});
}
return null;
} else {
return null;
}
}
As shown above, I have a debugPrint statement, this statement prints the returned videoPath from the filtersResultChannel
<--------->
THE PROBLEM
<--------->
Even though I'm successfully getting the videoPath value and successfully returning back to the Flutter page, I'm NOT able to use it!!
The setState(); doesn't update the UI NOR navigate to the next screen, the VideoShow screen!
HOW MAY I FIX SUCH AN ISSUE?

Facebook sdk 4.0.1 can't get some fields with Android studio

I am working on a login function with facebook for my android app.
I have almost everything done but i can't get all the fields.
Im getting only something in fullname and the fbid.
First name, Gender, Profile picture returns nothing.
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject fbUser,
GraphResponse response) {
final ParseUser parseUser = ParseUser.getCurrentUser();
try{
parseUser.fetchIfNeeded();
}catch (Exception e){}
if (fbUser != null && parseUser != null
&& fbUser.optString("name").length() > 0) {
Log.d("fb","Json--"+fbUser);
parseUser.put(USER_OBJECT_NAME_FIELD, fbUser.optString("first_name"));
parseUser.put("fullname",fbUser.optString("name"));
try{
String mm= fbUser.getString("email");
parseUser.setEmail(mm);
}catch (Exception e){//e.printStackTrace();
}
try{
String mm= fbUser.getString("gender");
if(mm.equals("male"))
{
For profile pic i'm using this:
try {
final String id = fbUser.getString("id");
parseUser.put("fbId", id);
//Your code goes here
String ur = "https://graph.facebook.com/" + id + "/picture?width=640&height=640";
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity().getApplicationContext()));
imageLoader.loadImage(ur, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap bmImg) {
// Do whatever you want with Bitmap
if(bmImg!=null) {
bmImg=Bitmap.createScaledBitmap(bmImg,640,640,false);
ParseFile dL = new ParseFile("dpLarge.jpg", bmImg.toString().getBytes());
Bitmap smal = Bitmap.createScaledBitmap(bmImg, 120, 120, false);
ParseFile ds = new ParseFile("dpSmall.jpg", smal.toString().getBytes());
parseUser.put("dpLarge", dL);
parseUser.put("dpSmall", ds);
}
Permissions:
facebookLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loadingStart(false); // Facebook login pop-up already has a spinner
if (config.isFacebookLoginNeedPublishPermissions()) {
ParseFacebookUtils.logInWithPublishPermissionsInBackground(getActivity(),
config.getFacebookLoginPermissions(), facebookLoginCallbackV4);
} else {
ParseFacebookUtils.logInWithReadPermissionsInBackground(getActivity(),
config.getFacebookLoginPermissions(), facebookLoginCallbackV4);
}
}
});
}
Can't figure out what im doing wrong.
I haven't already used facebook sdk, but according to your problem with a profile picture, did you tried solutions from these posts:
How to get facebook profile picture of user in facebook SDK 3.0 Android
How to get facebook profile picture of user in facebook SDK Android
Try also to use some logs for example to check if String ur appears correctly.

Create Session with Android Java Firebase

I am using email and password. I have create user and authenticate user but I don't know how to add a session for this user.
For example, if the user logs into his/her account. He/she is able to delete the application's process on their phone when they do not want to use the app, then get rid of the app's process and the session is should still be ongoing, therefore when they go back to their application they should still be logged in until he/she logs out (unauth).
I am having trouble making a session for a logged in user. I believe a token must be used but I have no idea how I should use it.
Login Activity:
Firebase user_data = new Firebase("https://myapp.firebaseio.com");
user_data.authWithPassword(login_email.getText().toString(), login_pwd.getText().toString(), new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Toast.makeText(getBaseContext(), "Login success!", Toast.LENGTH_LONG).show();
Intent toMainActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(toMainActivity);
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
System.out.println("ERROR.........................................");
}
});
Heres a simple scenerio:
User logs in. (From Login class is being Intent to Main activity class)
User does not log out but delete app's process.
Later User decides to use the app.
My problem: When click on app, it brings the user back to the Login page whereas it should brought the user to the Main Activity page.
Updated - Initialization
I have initialize it's still not saving the logged in state.
My problem: When click on app, it brings the user back to the Login page whereas it should brought the user to the Main Activity page.
Here's the Main Activity page:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_main);
Firebase user_data = new Firebase("https://myapp.firebaseio.com");
user_data.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
System.out.println("Authentication is currently working"); //this did print
} else {
System.out.println("Failed authentication");
}
}
});
AuthData authData = user_data.getAuth();
if (authData != null) {
System.out.println("The state is: " + authData); //this did print
} else {
System.out.println("Failed");
}
I check the authentication and they seem to be fine but when I delete the process after logging in at the Main Activity it jumps back to the Login page when I reload the app.
The results for monitoring the auth data above:
working auth
Authentication is currently working
state
The state is: AuthData{uid='simplelogin:3', provider='password', token='***', expires='1426758087', auth='{provider=password, uid=simplelogin:3}', providerData='{email=du16493#gmail.com, isTemporaryPassword=false}'}
Authentication is currently working
SOLVED
Just add the intent if authentication is currently running and it should straight back into the Main activity when the app first loads up on your phone at your first activity you called.
Here's the Login Activity page:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_main);
Firebase user_data = new Firebase("https://myapp.firebaseio.com");
user_data.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
System.out.println("Authentication is currently working"); //this did print
Intent toMainActivity = new Intent( getBaseContext(), MainActivity.class);
startActivity(toMainActivity);
} else {
System.out.println("Failed authentication");
}
}
});
AuthData authData = user_data.getAuth();
if (authData != null) {
System.out.println("The state is: " + authData); //this did print
} else {
System.out.println("Failed");
}
In order for authentication sessions to be persisted across application restarts, you'll need to initialize the Firebase Android client library with you Android context:
From https://www.firebase.com/docs/android/guide/setup.html:
The Firebase library must be initialized once with an Android context.
This must happen before any Firebase reference is created or used. You
can add the Firebase setup code to your Android Application's or
Activity's onCreate method.
#Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
// other setup code
}
The Firebase client will automatically be authenticated on subsequent application cold starts. To check authentication state, see Firebase Android: Monitoring Authentication.

Android Facebook Share not showing description on facebook wall

When my app try to share something, the description is shown in the share activity, but it does not show up when it is posted. I went through many stackoverflow posts, but nothing could solve my problem.
Here is my call flow :
Share button is clicked
Activity calls a static method and passes itself and content to share to it via Bundle
Share activity is invoked from this static method. It displays the content to share correctly with all image, caption and description
Content is shared successfully
When the facebook post is checked, it just shows the playstore app details, with the image that I had set in 3, without the description
Here is the code that i use
if (FacebookDialog.canPresentShareDialog(activity.getApplicationContext(),
FacebookDialog.ShareDialogFeature.SHARE_DIALOG))
{
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(activity)
.setLink("<playstore link>")
.setApplicationName("<appname>")
.setName("<some name>")
.setCaption("<some text>")
.setDescription("a description")
.setPicture("http://url/to/image.jpg")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
But sharing the same using FeedDialog works
Bundle params = new Bundle();
params.putString("name", "name");
params.putString("caption", "caption");
params.putString("description","desc");
params.putString("link", "playstore link");
params.putString("picture", "http://url/to/image.jpg");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(activity,
session,
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(activity,
"Posted Successfully!",
Toast.LENGTH_SHORT).show();
activity.finish();
} else {
// User clicked the Cancel button
Toast.makeText(activity.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
activity.finish();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(activity.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
activity.finish();
} else {
Toast.makeText(activity.getApplicationContext(),
"An Error Occurred",
Toast.LENGTH_SHORT).show();
activity.finish();
}
}
})
.build();
feedDialog.show();
Thank You
From the docs (Versions 4.0+)
To show the ShareDialog for a link in your activity, create a
ShareDialog instance in your onCreate method:
public class MainActivity extends FragmentActivity {
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
// this part is optional
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() { ... });
}
Then show the ShareDialog:
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription(
"The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
Slartibartfast's Answer is working fine until compile 'com.facebook.android:facebook-android-sdk:4.24.0'
From Facebook SDK version 4.25.0
setContentTitle("") setContentDescription("") is depricated.
You have to use setQuote(""); Method instead of setContentDescription("");
For more detail about depreciation Refer: https://developers.facebook.com/docs/sharing/android

Facebook SDK on Android: WebDialog closing after giving authorization

I'm creating an app for Android and I've integrated the Facebook SDK to present the users a Feed Dialog with the following code:
public void showDialog()
{
Bundle parameters = new Bundle();
parameters.putString("description", "description about link");
parameters.putString("link", "http://google.nl");
parameters.putString("name","Name of link");
parameters.putString("caption","describe your caption text");
parameters.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = new WebDialog.FeedDialogBuilder(this, Session.getActiveSession(), parameters).build();
feedDialog.show();
}
I call this method after I've created the session:
public void onClick(View v)
{
Session.StatusCallback callback = new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
if(session.isOpened()) showDialog();
}
};
Session.openActiveSession(this, true, callback);
}
The WebDialog comes up and I can login. Then It says that I've already authorized this app but after that, the dialog closes without a warning or something. I don't know why this is the case: all the parameters seems to be ok. Can anyone help me with this and explain why the dialog disappears?

Categories

Resources