ShareDialog doesn't open facebook app - android

Trying to implement facebook sharing, however it only works in webview if I set ShareDialog.Mode.AUTOMATIC, if I set it to NATIVE then nothing shows up at all and I don't receive no error callback. Facebook app is installed in the emulator.
Provider in manifest:
<provider android:authorities="com.facebook.app.FacebookContentProvider{myAppId}"
android:name="com.facebook.FacebookContentProvider"
android:exported="true"/>
Code for sharing:
public void share(String contentUrl,
Activity activity){
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(contentUrl))
.build();
ShareDialog dialog = new ShareDialog(activity);
dialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
EventBus.getDefault().post(new ShareEvent(true));
}
#Override
public void onCancel() {
Log.e(TAG, "Facebook Share Cancel");
EventBus.getDefault().post(new ShareEvent(false));
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "Facebook share error: " + error.getMessage());
EventBus.getDefault().post(new ShareEvent(false));
}
})
dialog.show(content, ShareDialog.Mode.NATIVE);
}
I'm calling share(..) method from fragment.
I tried implementing sharing using intents, and that works
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://myUrl.com");
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ((app.activityInfo.name).contains("facebook")) {
final ActivityInfo mActivity = app.activityInfo;
final ComponentName name = new ComponentName(mActivity.applicationInfo.packageName, mActivity.name);
shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
shareIntent.setComponent(name);
activity.startActivity(shareIntent);
break;
}
}
However in my case I need successful share callback, which as much as I know my last solution doesn't provide, since it always return result CANCELED

Have you declared permission for it? Like below:
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions"); // permission.
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// do something here
finish();
}
#Override
public void onCancel() {}
#Override
public void onError(FacebookException exception) {}
});
This is my sample code: https://github.com/minhhuy150894/simple-puzzle/blob/master/app/src/main/java/xyz/davidng/puzzle/FacebookShareImage.java

Related

Using Picasso to get Facebook profile picture at login

I have searched the internet high and low and cannot find a solution to this problem that works for me. When the user signs into the app using the facebook login button, I want to get their Facebook profile picture and use it as their profile picture in my app. I'm trying to use Picasso to get the picture from the Facebook URL. Here is my code as it is. I'm getting an error
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (getIntent().getBooleanExtra("EXIT", false)) {
}
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
loginButton = (LoginButton) findViewById(R.id.fb_login_btn);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken
oldAccessToken, AccessToken currentAccessToken) {
}
};
accessToken = AccessToken.getCurrentAccessToken();
if (AccessToken.getCurrentAccessToken() == null) {
loginButton.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Picasso.with(this) //I'm getting an error here "Picasso
cannot be applied"
.load("https://graph.facebook.com/" +
loginResult.getAccessToken().getUserId(); +
"/picture?type=large")
.into(profilePhoto);
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
{
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
}
finish();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancelled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Login Error",
Toast.LENGTH_SHORT).show();
}
});
} else {
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
this.finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
#Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
}
}
The problem is with this part
Picasso.with(this) //I'm getting an error here "Picasso
cannot be applied"
.load("https://graph.facebook.com/" +
facebook_id + "/picture?type=large")
.into(profilePhoto);
Here instead of 'this' you need to pass activity or application context.
If you are in activity then type 'YourActivityName.this' or if you are in fragment then use 'getActivity'.
If you are thinking why 'this' is not working then FYI 'this' here means anonymous inner class.
try this
loginButton.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken().getUserId();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
if (object.has("picture")) {
//String profilePicUrl="http://graph.facebook.com/"+object.getString("id")+"/picture?type=large";
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
profilePicUrl = profilePicUrl.replace("\\", "");
Picasso.with(YourActivity.this)
.load(profilePicUrl)
.into(profilePhoto);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
{
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
}
finish();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancelled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Login Error",
Toast.LENGTH_SHORT).show();
}
});

android Facebook SDK cannot share image

I am developing an app that can share an image to Facebook.
Only I can share image, other people cannot share. I have a FAB and calling this activity on its onClick() method. I really don't know what to do, my app is live but when I click on my app name over the shared photo I get
"Misconfigured App
Sorry, MyApp hasn't been approved for display in App Centre."
What is the reason that others cannot share images? I really need the answer. Thanks.
public class ShareActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private LoginManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
//this loginManager helps you eliminate adding a LoginButton to your UI
manager = LoginManager.getInstance();
manager.logInWithPublishPermissions(this, permissionNeeds);
manager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
sharePhotoToFacebook();
Toast.makeText(ShareActivity.this, "Success", Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onCancel() {
Toast.makeText(ShareActivity.this, "Cancel", Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(ShareActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
});
}
}
private void sharePhotoToFacebook(){
try {
URL url = new URL("http://burakakyalcin.site/image.png");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption("Hello")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
} catch(IOException e) {
System.out.println(e);
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
}

How do I use SharedPreferences with Facebook SDK?

Currently this is how my FB login looks like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TAG = "Login.Activity";
//Callback manager manages callbacks into the FB SDK from an Activity's onActivityResult() Method.
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
//If login in successful,
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
goMainScreen(profile);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(),R.string.cancel_login, Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), R.string.error_login, Toast.LENGTH_LONG).show();
}
});
}
private void goMainScreen(Profile profile) {
if(profile != null){
//Passing in the name,id and photo from the profile.
Intent intent = new Intent(this, MainActivity.class);
// intent.putExtra("name",profile.getName());
intent.putExtra("id",profile.getId());
intent.putExtra("photo",profile.getProfilePictureUri(200,200));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
//All Request Code, Result Code, and data are recieved by the activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
}
I would like to keep track of the user session throughout other activities and know if they have logged in before.Would I use sharedpreferences for this? If so will I be doing this at the beginning of the loginActivity?
Well you could use what provide the SDK and create a method like this one :
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}

Sharing content on Facebook at onClick in RecyclerView

I am trying to share the app content on facebook in an onClick method inside RecyclerView. Recyclerview works fine and showing data properly before the onclick method.
All the dependencies and other stuff is being done in gradle file etc... The problem i am facing is as soon as the user clicks share button, new intent is generated, I am passing relevant parameters but activity doesn't perform any action.
Below is the code for opening Facebook(HomeActivity) onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.home);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
imageURL= null;
position=0;
} else {
imageURL= extras.getString("imageURL");
//position = extras.getInt("position");
}
} else {
imageURL= (String) savedInstanceState.getSerializable("imageURL");
//position= (int) savedInstanceState.getSerializable("position");
}
callbackManager = CallbackManager.Factory.create();
// loginDataBaseAdapter = new LoginDataBaseAdapter(this);
// loginDataBaseAdapter = loginDataBaseAdapter.open();
facebookLogin = (LoginButton) findViewById(R.id.login_button);
facebookLogin.registerCallback(callbackManager, callback);
}
And this is what I am doing during call back method, it login successfully but crashes afterwards.
public FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// Toast.makeText(getApplicationContext(),"On facebook",Toast.LENGTH_LONG).show();
AccessToken accessToken = loginResult.getAccessToken();
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(imageURL))
.build();
ShareDialog.show(HomeActivity.this, content);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Profile profile = Profile.getCurrentProfile();
textView.setText("Connection Lost ! Pleasr Try Again :" + profile.getName());
}
};
And this is how onClick() method is written:
#Override
public void onClick(View v) {
Intent intent = new Intent(context.getApplicationContext(),HomeActivity.class);
intent.putExtra("position",getAdapterPosition());
intent.putExtra("imageURL",uri);
context.startActivity(intent);
}
Can somebody guide me through this. I am not very experienced in making apps and sharing content on social apps. Any help would be highly appreciated.
You can directly share on facebook by using
try {
Intent intent1 = new Intent();
intent1.setClassName("com.facebook.katana", "com.facebook.katana.activity.composer.ImplicitShareIntentHandler");
intent1.setAction(Intent.ACTION_SEND);
intent1.setType("text/plain");
intent1.putExtra(Intent.EXTRA_TEXT, "any text");
startActivity(intent1);
} catch (Exception e) {
Intent intent = new Intent(Intent.ACTION_SEND);
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + "any constant";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
intent.putExtra(Intent.EXTRA_TEXT, "any text");
startActivity(intent);
}
i.e. try to share on facebook app. if the app is not installed on device the share will be opened on browser

How to Share Our Own Static Status in Facebook using Android

I am developing an application.
In that I am trying to share information of my application as a Status of Facebook and Twitter when button is clicked.
When I click on twitter button the status as I want to share is twitted automatically but In facebook I cant share info as I want in show blank textbox of facebook share status window.
Where I am wrong please tell me ?
This is my code.
final String msg="Hie - " +
"Message to share";
#Override
protected void onCreate(Bundle savedInstanceState)
{
.....................
.....................
static SocialAuthAdapter adapter;
adapter = new SocialAuthAdapter(new ResponseListener());
try
{
adapter.addConfig(Provider.TWITTER, "key", "BsiY4LH5Y4naSmb.............",null);
}
catch (Exception e)
{
e.printStackTrace();
}
imgtellfriend.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.sequence);
imgtellfriend.startAnimation(anim);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, msg);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
imgFb.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.sequence);
imgFb.startAnimation(anim);
adapter.authorize(Catagories.this, Provider.FACEBOOK);
initShareIntent("com.facebook.katana");
}
});
imgtwiter.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.sequence);
imgtwiter.startAnimation(anim);
adapter.authorize(Catagories.this, Provider.TWITTER);
}
});
}
private final class ResponseListener implements DialogListener
{
#Override
public void onComplete(Bundle values)
{
Log.d("Share-Bar", "Authentication Successful");
final String providerName = values.getString(SocialAuthAdapter.PROVIDER);
Log.d("Share-Bar", "Provider Name = " + providerName);
Toast.makeText(Catagories.this, providerName + " connected", Toast.LENGTH_SHORT).show();
adapter.updateStatus(msg, new MessageListener(), true);
}
#Override
public void onCancel()
{
Log.d("Share-Bar", "Authentication Cancelled");
}
#Override
public void onBack()
{
Log.d("Share-Bar", "Dialog Closed by pressing Back Key");
}
#Override
public void onError(SocialAuthError error)
{
initShareIntent("com.facebook.katana");
error.printStackTrace();
Log.d("Share-Bar 1", error.toString());
Log.d("Share-Bar 2", error.getMessage());
}
}
#SuppressLint("DefaultLocale")
private void initShareIntent(String type)
{
boolean found = false;
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
// gets the list of intents that can be loaded.
List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty()){
for (ResolveInfo info : resInfo) {
Log.d("MEssage FB","--------- App :: "+info.activityInfo.packageName.toLowerCase());
if (info.activityInfo.packageName.toLowerCase().contains(type) ||
info.activityInfo.name.toLowerCase().contains(type) )
{
share.putExtra(Intent.EXTRA_SUBJECT, "ECard");
share.putExtra(Intent.EXTRA_TEXT, msg);
share.setPackage(info.activityInfo.packageName);
found = true;
break;
}
}
if (!found)
return;
startActivity(Intent.createChooser(share, "Select"));
}
}
private class MessageListener implements SocialAuthListener<Integer>
{
#Override
public void onExecute(String provider, Integer t)
{
Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 || status.intValue() == 204)
Toast.makeText(Catagories.this, "Message posted on " + provider, Toast.LENGTH_LONG).show();
else
Toast.makeText(Catagories.this, "Message not posted on " + provider, Toast.LENGTH_LONG).show();
}
#Override
public void onError(SocialAuthError e) {
}
I am using socialauth library for that.
SocialAUth Android new version is working for facebook. The only thing is you need to use native facebook android login.
socialauth library uses old facebook sdk.
dont use that.
you can directly use intent filter to share on social networks.
[Updated one]
check this
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/png");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"YOUR TEXT HERE");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,"YOUR TEXT HERE");
shareIntent.putExtra(android.content.Intent.EXTRA_STREAM,pngUri);
PackageManager pm = getApplicationContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ((app.activityInfo.name).contains("facebook")) {
final ActivityInfo activity = app.activityInfo;
final ComponentName name = new ComponentName(
activity.applicationInfo.packageName,
activity.name);
shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
shareIntent.setComponent(name);
startActivity(shareIntent);
}
}
}

Categories

Resources