Android studio twitter check if user is logged in - java

I have followed twitter fabric log in and everything is working fine except for the part where i try to post a tweet. When i execute this following code i need to login again, so it seems like i have to check an access token or some, but i have no idea and can't find how to do that.
#Override
public void onCreate(Bundle savedInstanceState) {
//initialize facebook sdk
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
super.onCreate(savedInstanceState);
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
if (token != null ) {
Log.d(TAG, "twitter token" + token);
}
if (secret != null ) {
Log.d(TAG, "twitter secret" + secret);
}
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this.getActivity(), new TwitterCore(authConfig), new TweetComposer());
}
then i am using a function to post the tweet
public void TwitterSharing() {
Log.d(TAG, "Running twitter share");
Log.d(TAG, "Share on twitter 1: " + sport);
Log.d(TAG, "Share on twitter 2: " + speed);
Log.d(TAG, "Share on twitter 3: " + distance);
Log.d(TAG, "Share on twitter 4: " + date);
Log.d(TAG, "Shared image url: " + sharedImage);
TweetComposer.Builder builder = new TweetComposer.Builder(this.getActivity())
.text("just setting up my Fabric.")
.image(Uri.parse(sharedImage));
builder.show();
}
It all works but on the web page it is loading i need to login again, that should not happen but i have no idea how.
Thanks for any input.

For that, you need to make an Activity as the launcher activity. Let's call it DispatchActivity
public class DispatchActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
This returns true if user is logged in.
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn){
//User is logged in, take him to your activity
Intent i = new Intent(this,yourMainActivity.class);
this.startActivity(i);
}
else{
//User is not logged in, take him to your SignIn activity
Intent i = new Intent(this,SignUp.class);
this.startActivity(i);
}
}
}
Remember to make this your launcher activity, and don't create a layout file for it.

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?

Android In-App Billing: Ads are not removing when In-App is made

I have implemented In-App Billing in my Activity
this is my onIabPurchaseFinished() method:
#Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
if (!verifyDeveloperPayload(info)) {
Toast.makeText(this, R.string.error_purchasing, Toast.LENGTH_LONG).show();
}
Toast.makeText(this, R.string.premium_bought, Toast.LENGTH_LONG).show();
if (info.getSku().equals("chords_premium")) {
/** salva isPremium tra SharedPreferences */
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("status", "purchased");
editor.apply();
}
}
As you can see I save the String "status" to SharedPreferences so that I can access it from anywhere, and keep it stored even after the app is closed.
Then in my other Activities where ads are implemented I wrote like this:
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final String status = prefs.getString("status", "free");
/** gestisce le pubblicita */
if (status.equals("free")) {
MobileAds.initialize(getApplicationContext(), "ca-app-pub-6723047396589178/2654753246");
AdView listBanner = (AdView) findViewById(R.id.chords_list_banner);
AdRequest adRequest = new AdRequest.Builder().build();
listBanner.loadAd(adRequest);
/** carica Ad a tutto schermo */
chordsListAd = new InterstitialAd(this);
chordsListAd.setAdUnitId("ca-app-pub-6723047396589178/7447672046");
requestNewInterstitial();
chordsListAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
}
As you can see here the Ads are surrounded by an if statement that checks if the "status"String is set to free.
The problem is that when I buy Premium, the Ads are still shown. How can I fix it?
It's because you are saving your data in Base Context and trying to find it in the current Activity context using (this).
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
to
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Also, a more recommeded way to query In-App purchased items is to query In- App inventory instead of storing in sharedprefs.
As mention in Google Docs
Query Purchased Items
Upon a successful purchase, the user’s purchase data is cached locally by Google Play’s In-app Billing service. It is good practice to frequently query the In-app Billing service for the user’s purchases, for example whenever the app starts up or resumes, so that the user’s current in-app product ownership information is always reflected in your app.
To retrieve the user’s purchases from your app, call queryInventoryAsync(QueryInventoryFinishedListener) on your IabHelper instance. The QueryInventoryFinishedListener argument specifies a listener that is notified when the query operation has completed and handles the query response. It is safe to make this call fom your main thread.
mHelper.queryInventoryAsync(mGotInventoryListener); //mHelper is IabHelper instance
If the query is successful, the query results are stored in an Inventory object that is passed back to the listener. The In-app Billing service returns only the purchases made by the user account that is currently logged in to the device.
IabHelper.QueryInventoryFinishedListener mGotInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else {
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
// update UI accordingly
}
}
};
Check if the inapp purchase is made:
//*************************************checking in app purchase has been made********************************//
void testInApp()
{
if (!blnBind) return;
if (mService == null) return;
int result;
try {
result = mService.isBillingSupported(3, getPackageName(), "inapp");
//Toast.makeText(context, "isBillingSupported() - success : return " + String.valueOf(result), Toast.LENGTH_SHORT).show();
Log.i(tag, "isBillingSupported() - success : return " + String.valueOf(result));
} catch (RemoteException e) {
e.printStackTrace();
//Toast.makeText(context, "isBillingSupported() - fail!", Toast.LENGTH_SHORT).show();
Log.w(tag, "isBillingSupported() - fail!");
return;
}
}
void checkInApp()
{
if (!blnBind) return;
if (mService == null) return;
Bundle ownedItems;
try {
ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
//Toast.makeText(context, "getPurchases() - success return Bundle", Toast.LENGTH_SHORT).show();
Log.i(tag, "getPurchases() - success return Bundle");
} catch (RemoteException e) {
e.printStackTrace();
//Toast.makeText(context, "getPurchases - fail!", Toast.LENGTH_SHORT).show();
Log.w(tag, "getPurchases() - fail!");
return;
}
int response = ownedItems.getInt("RESPONSE_CODE");
//Toast.makeText(context, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response), Toast.LENGTH_SHORT).show();
Log.i(tag, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response));
if (response != 0) return;
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_ITEM_LIST\" return " + ownedSkus.toString());
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_DATA_LIST\" return " + purchaseDataList.toString());
Log.i(tag, "getPurchases() - \"INAPP_DATA_SIGNATURE\" return " + (signatureList != null ? signatureList.toString() : "null"));
Log.i(tag, "getPurchases() - \"INAPP_CONTINUATION_TOKEN\" return " + (continuationToken != null ? continuationToken : "null"));
// TODO: management owned purchase
try {
if(purchaseDataList.size()>0){
jinapp=new JSONArray(purchaseDataList.toString());
JSONObject c = jinapp.getJSONObject(0);
String productid=c.getString("productId");
if(productid!=null){
SharedPreferences.Editor editor = prefpurchase.edit();
editor.putBoolean(Constants.APP_IS_PURCHASED,true);
editor.commit();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO: management owned purchase
}
Write the code in your SplashScreen
Now in the activity/fragment in which you are showing your ad,write the following code:
//*******************to check purchase has been made.If yes disable ads and no then show ads******************//
prefpurchase = this.getSharedPreferences(Constants.GET_IN_APP_STATE, Context.MODE_PRIVATE);
//Toast.makeText(context, "bindService - return " + String.valueOf(blnBind), Toast.LENGTH_SHORT).show();
//In App Purchase
ispurchased=prefpurchase.getBoolean(Constants.APP_IS_PURCHASED,false);
System.out.println("ispurchased-->"+ispurchased);
if(ispurchased)
{
setContentView(R.layout.activity_home_noads);
}else{
System.out.println("Getting ad");
setContentView(R.layout.activity_home);
//Locate the Banner Ad in activity_main.xml
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
// Add a test device to show Test Ads
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
//.addTestDevice("B2D63***************************")
.build();
// Load ads into Banner Ads
adView.loadAd(adRequest);
}
//*******************************************************************************************************//
The logic is simple,you are creating two versions of your layout,one with ad and the other without ad.
Load the correct layout depending on the value of sharedpreference.
mService:
Write this code globally in splashscreen before onCreate():
private IInAppBillingService mService;
private ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
blnBind
Declare blnBind globally:
boolean blnBind;
In onCreate() of SplashActivity write:
// Bind Service
blnBind = bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
//Toast.makeText(context, "bindService - return " + String.valueOf(blnBind), Toast.LENGTH_SHORT).show();
Log.i(tag, "bindService - return " + String.valueOf(blnBind));
//In App Purchase
GET_IN_APP_STATE or APP_IS_PURCHASED are created for shared Preferences,that acts as a key for preference values.
//Preferences to check in app purchase
final static public String GET_IN_APP_STATE = "prefinapp";
public static final String APP_IS_PURCHASED ="AppIsPurchased";
Whenever a purchase is made,don't forget to set the shared preference value to true.

Facebook share completion listener

I have something i am really stuck at. The thing is that i am trying to catch the completion when some one is done with sharing something on facebook
i am using the following function to execute and catch the completion. But i am not getting the result.
public void FaceBookSharing() {
Log.d(TAG, "Running facebook share");
Log.d(TAG, "Share on facebook 1: "+sport);
Log.d(TAG, "Share on facebook 2: "+speed);
Log.d(TAG, "Share on facebook 3: "+distance);
Log.d(TAG, "Share on facebook 4: "+date);
Log.d(TAG, "Shared image url: "+sharedImage);
callbackManager = CallbackManager.Factory.create();
final ShareDialog shareDialog = new ShareDialog(this);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.d(TAG, "success");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "error");
}
#Override
public void onCancel() {
Log.d(TAG, "cancel");
}
});
ShareLinkContent shareLinkContent = new ShareLinkContent.Builder()
.setContentTitle("Mijn workout "+sport+" | " +speed+" | "+ distance+" | "+ date+" is gesponsord door "+Company)
.setContentDescription(shareDesc)
.setContentUrl(Uri.parse(mUrl))
.setImageUrl(Uri.parse(sharedImage))
.build();
ShareDialog.show(advertise.this,shareLinkContent);
}
I have searched everywhere and i am unable to find a suiting solution to my problem also i am not really good with listeners.
Thank you.
I have solved as i forgot to init the call back in oncreate.

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

Categories

Resources