I am having some trouble while trying to share content from my app into Facebook.
I am using the following code to do it:
facebookButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(ShareDialog.canShow(ShareLinkContent.class)){
ShareLinkContent linkContent=new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(imageUrls.get(0)))
.build();
shareDialog.show(linkContent, ShareDialog.Mode.WEB);
}
}
});
My images are stored on Firebase Storage and I am able to post on Facebook as well but the title and description are both set to firebasestorage.googleapis.com like this linked image:
screenshot of share post
Note : The setContentDescription() and setContentTitle() and setImageUrl() are all deprecated.
Is there a way to set the title,and description of the shared post?
FadyDev, I don't know if you've already resolved your problem but this is what I do in place of deprecated codes:
// Builds the object
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("fb:app_id", my_app_ID)
.putString("og:url", link_to_site)
.putString("og:type", objectType)
.putString("og:title", contentTitle)
.putString("og:description", contentDescription)
.putString("og:image", imageLink)
.build();
// Builds the action
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType(actionName)
.putObject(objectName, object)
.build();
// Create the openGraphContent
ShareOpenGraphContent openGraphContent = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName(objectName)
.setAction(action)
.build();
return openGraphContent;
Look in the facebook doc for what action you want to use and there corresponding object type and required parameters.
https://developers.facebook.com/docs/sharing/opengraph/using-actions
https://developers.facebook.com/docs/reference/opengraph
Hope this helps!
Related
Apply Deep Linking in flutter app to open
a specific page in another app or same app
i want to know to how implement deep links in flutter
or open channel with android native and ios native ?
?
I think it would be the same as in a normal android app. Deeplinking is a configuration thing rather than code.
You need to write some things in your android manifest.
Have a look at the firebase manual for deep linking:
Firebase deeplinking manual
You can use firebase dynamic links for deep linking in a flutter. Refer this link for full implement steps and create and receive a link, https://medium.com/better-programming/deep-linking-in-flutter-with-firebase-dynamic-links-8a4b1981e1eb.
Here is a sample code for receiving a link inside the app and open a new screen.
class MainWidgetState extends State<MainWidget> {
#override
void initState() {
super.initState();
this.initDynamicLinks();
}
initDynamicLinks(BuildContext context) async {
await Future.delayed(Duration(seconds: 3));
var data = await FirebaseDynamicLinks.instance.getInitialLink();
var deepLink = data?.link;
final queryParams = deepLink.queryParameters;
if (queryParams.length > 0) {
var userName = queryParams['userId'];
openNewScreen(userName);
}
FirebaseDynamicLinks.instance.onLink(onSuccess: (dynamicLink)
async {
var deepLink = dynamicLink?.link;
final queryParams = deepLink.queryParameters;
if (queryParams.length > 0) {
var userName = queryParams['userId'];
openNewScreen(userName);
}
debugPrint('DynamicLinks onLink $deepLink');
}, onError: (e) async {
debugPrint('DynamicLinks onError $e');
});
}
openNewScreen(String userName){
Navigator.of(context).pushNamed("routeFormScreen", arguments: {"name": userName});
}
}
I am trying to post a Custom Open graph story in Facebook integration with SDK 4.5 , but i am not able to post it. i have created a object and action in my code
I am getting this error:
Failed to generate preview for user.com.facebook.http.
protocol.ApiException: [code] 100 [message]: (#100)
App xxxx is not allowed to create actions of type
restaurant:Wants To Visit for user xxxxx [extra]:
My code:
public void SongRequest(){
try {
// Create an object
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "restaurant.restaurant")
.putString("og:title", "Peddlers")
.putString("og:image", "https://scontent.fdel1-1.fna.fbcdn.net/hphotos-xpt1/v/t1.0-9/11996901_943588275699701_6661729706633501716_n.jpg?oh=5ebb6e29eff2009e0f4c68f86b06923d&oe=56A8B7CE")
.putString("og:description", "Peddlers Under The Big Ben")
.putString("restaurant:contact_info:street_address", "1601 Willow Rd.")
.putString("restaurant:contact_info:locality", "Menlo Park")
.putString("restaurant:contact_info:region", "California")
.putString("restaurant:contact_info:postal_code", "160022")
.putString("restaurant:contact_info:country_name", "India")
.putString("restaurant:contact_info:email", "brian#example.com")
.putString("restaurant:contact_info:phone_number", "212-555-1234")
.putString("restaurant:contact_info:website", "https://www.facebook.com/peddlersrock")
.putString("place:location:latitude", "30.70516586")
.putString("place:location:longitude", "76.8010025")
.putString("og:url", "https://www.facebook.com/CompetentGroove")
.build();
//Then create an action and link the object to the action.
// Create an action
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("restaurant.wants_to_visit")
.putObject("restaurant", object)
.build();
//Finally, create the content model to represent the Open Graph story.
// Create the content
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("restaurant")
.setAction(action)
.build();
//Present the Share dialog by using the show method on ShareDialog.
ShareDialog.show(HelloFacebookSampleActivity.this, content);
} catch (Exception e) {
Log.e("Graph Stories.Exception", e.toString());
}
}
I am new to azure but i know certain things like how to retrieve and store data to azure , i followed azure official documentation for this purpose.
Link is Here - https://azure.microsoft.com/en-in/documentation/articles/mobile-services-android-get-started-data/
But the problem is, this tutorial is only showing How to retrieve and use Data from azure using Adapters and Lists . I want to know , How can i retrieve a single value from azure mobile services and how to use it in android.
Plzz provide me both backend code (if there is any) and java code for this . THANKS in advance
I got it solved. No need to create a custom API.
Just follow the basics , Here is the code :-
final String[] design = new String[1];
private MobileServiceTable<User> mUser;
mUser = mClient.getTable(User.class);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<User> result =
mUser.where().field("name").eq(x).execute().get();
for (User item : result) {
// Log.i(TAG, "Read object with ID " + item.id);
desig[0] = item.getDesignation(); //getDesignation() is a function in User class ie- they are getters and setters
Log.v("FINALLY DESIGNATION IS", desig[0]);
}
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
designation.setText(desig[0]);
}
}.execute();
DON'T forget to create a class User for serialization and all. Also you should define the array .
FEEL FREE to write if you got it not working.
EDIT :-
design[0] is an array with size 1.
eq(x) is equal to x where , x variable contains username for which i want designation from database (azure).
You can do this with a custom API. See this link: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-use-server-scripts/#custom-api
Code looks like this:
exports.post = function(request, response) {
response.send(200, "{ message: 'Hello, world!' }");
}
It's then reachable at https://todolist.azure-mobile.net/api/APIFILENAME.
If you want to access a table you can do something like:
exports.post = function(request, response) {
var userTable = tables.getTable('users');
permissionsTable
.where({ userId: user.userId})
.read({ success: sendUser });
}
function sendUser(results){
if(results.length <= 0) {
res.send(200, {});
} else {
res.send(200, {result: results[0]});
}
}
You can then follow the instructions for using the API on your Android client here: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-call-custom-api/
How your app is written will change how this code works/looks, but it looks something like:
ListenableFuture<MarkAllResult> result = mClient.invokeApi( "UsersAPI", MarkAllResult.class );
That invokes the API. You need to write the class and Future to handle the results. The above page explains this in great detail.
The most optimal solution would be to create an api on your server which accepts an ID to return an single object/tablerow.
In your android app, you only have to call:
MobileServiceTable<YourClass> mYourTable;
mClient = new MobileServiceClient(
"https://yoursite.azurewebsites.net/",
mContext);
mYourTable = mClient.getTable(YourClass.class);
YourClass request = mYourTable.lookUp(someId).get();
// request -> https://yoursite.azurewebsites.net/tables/yourclass/someId
YourClass should have the same properties as the object on the server.
I want to post a predefind message with link on facebook wall without user intervention .I mean user just log into facebook and my predefind message should be post with link on user's facebook wall.
Below is my code.
public class PostOnFacebookWall {
public static void postOnWall(Facebook facebook , final Context context, final String placeName) {
Bundle params = new Bundle();
params.putString("message", placeName);
facebook.dialog(context, "feed", params ,new DialogListener() {
public void onFacebookError(FacebookError e) {
}
public void onError(DialogError e) {
}
public void onComplete(Bundle values) {
Toast.makeText(context, placeName+" for today's hangout has been posted on your facebook wall. ", Toast.LENGTH_LONG).show();
}
public void onCancel() {
}
});
}
}
I've looked so many links about my question like below
http://stackoverflow.com/questions/11316683/adding-content-to-facebook-feed-dialog-with-new-facebook-sdk-for-android
which passed all the parameter like "link","description","image" and much more.
Someone is saying that u have to pass all the parameters.I just want to predefind messages and link over that.
My message is should be "Let's hangout at " and here placeName should be a link.
And this complete msg i want to pass from my code .I don't want that my code opens dialog where user enters it's message.
If you need to post a predefined message to a User's Facebook Wall, you shouldn't be using the facebook.dialog method.
For more on why that shouldn't be used, read my answer posted here: https://stackoverflow.com/a/13507030/450534
That being said, to get the result you want, try this piece of code:
Bundle postStatusMessage = new Bundle();
// ADD THE STATUS MESSAGE TO THE BUNDLE
postStatusMessage.putString("message", "Let's hangout at " + placeName);
postStatusMessage.putString("link", "www.the_example_web_address.com");
Utility.mAsyncRunner.request("me/feed", postStatusMessage, "POST", new StatusUpdateListener(), null);
And this is where you can check the response from the Facebook API by parsing the String response:
private class StatusUpdateListener extends BaseRequestListener {
#Override
public void onComplete(String response, Object state) {
}
A point to note here is, you cannot pass a message with a link in it. To elaborate (as the earlier statement might sound confusing), You cannot pass a link in the message tag with a link that will be parsed by Facebook and show up in a post like links on FB do.
To see the difference clearly, post the status update using the code above and see how it looks on Facebook. Then, after having done that, remove this postStatusMessage.putString("link", "www.the_example_web_address.com"); from the code above and include the link in the message tag, post it and see how it looks on Facebook.
I'm trying to integrate posting to one's wall from within my app. I already have an area where the user can save his/her username and password (encrypted). I would like my program to recall the saved username and password, pass that to Facebook for authentication, and then allow the app to post simple text (maybe a link too) to the user's wall.
That said, I've read everything on the developer pages at Facebook (the api looks completely foreign to me... I've never done any type of web app development before... just desktop apps), and experimented with the Java libraries here but to be honest, I don't understand any of the various implementations. Some claim to be simple to use, but apparently they are all way above my head.
I've even tried messing with the official Facebook Android SDK, but that uses a webview interface, and I can't pass in the username and password for easy authentication. Plus, I'm still clueless as to how to post to the wall even after correct authentication.
Please help.
Thanks.
Oh, btw I already have a Facebook API key and Application ID.
[UPDATE 1]
For further clarification:
If I use the following code snippet with the official Facebook Android SDK http://github.com/facebook/facebook-android-sdk what should I do next (after the user has logged-in)? This is unclear to me.
Facebook facebookClient = new Facebook();
facebookClient.authorize(this, "[APP ID]", new String[] {"publish_stream", "read_stream", "offline_access"}, this);
where "this" is an Activity that implements a DialogListener, and "[APP ID]" is my Facebook application ID.
Thanks.
[UPDATE 2]
I found a solution (see below), though the only thing missing is the ability to auto-populate the login text boxes with the data I have stored in the app. The official Facebook Android SDK may not allow for this. I'll keep looking into it.
I figured it out, with Tom's help (thanks). The key was creating a dialog with the "stream.publish" API call, using the Facebook Android SDK. Here are the steps:
Download the official Facebook Android SDK : http://github.com/facebook/facebook-android-sdk
Import the project files into Eclipse.
Export the project as a *.jar file. (this might cause a conflict)
[UPDATE]
Facebook recently updated the source code and I noticed the icon file caused resource id conflicts with my projects (Android 1.5+). My solution is to forget about exporting as a jar. Instead, copy the Facebook "com" folder directly into your app's "src" folder (i.e. "com.facebook.android" should be a package in your app... right alongside your source files). If you already have a "com" folder in your "src" folder, don't worry about any dialog boxes that appear about overwriting files, none of your source files should be overwritten. Go back into Eclipse, and refresh the "src" folder and "com.facebook.android" should now be listed as a package. Copy one of the included Facebook icons to your app's "drawable" folder and refresh that as well. Eclipse will complain about the "FbDialog.java" file... just add an import pointing to your app's "R" file to the header of that file (e.g. if your app's package name is "com.android.myapp," then add this: "import com.android.myapp.R;"). Go to #5 if you needed to do this.
Add the .jar file to your project's build path
Look at the following simplified example code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import com.facebook.android.*;
import com.facebook.android.Facebook.DialogListener;
public class FacebookActivity extends Activity implements DialogListener,
OnClickListener
{
private Facebook facebookClient;
private LinearLayout facebookButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test);//my layout xml
facebookButton = (LinearLayout)this.findViewById(R.id.Test_Facebook_Layout);
}
#Override
public void onComplete(Bundle values)
{
if (values.isEmpty())
{
//"skip" clicked ?
return;
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "post_id" is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("post_id"))
{
try
{
Bundle parameters = new Bundle();
parameters.putString("message", "this is a test");// the message to post to the wall
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
#Override
public void onError(DialogError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onCancel()
{
}
#Override
public void onClick(View v)
{
if (v == facebookButton)
{
facebookClient = new Facebook();
// replace APP_API_ID with your own
facebookClient.authorize(this, APP_API_ID,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
}
}
AsyncFacebookRunner mAsyncRunner;
Facebook facebook =new Facebook("Your app id");
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = facebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
Here is an objective answer to your new question, "What do I do next?"
A quick look at the source code leads me to believe this is what you do:
Check this URL for the REST (http://en.wikipedia.org/wiki/Representational_State_Transfer) API methods you can use to leave a comment/post:
http://developers.facebook.com/docs/reference/rest/
Specifically this: http://developers.facebook.com/docs/reference/rest/links.post
Check out lines 171 through 295 of Facebook.java
http://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/android/Facebook.java
To see how to use the API to make these requests.
You'll probably want this method (it's overloaded, see the code).
/**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
*
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* String response = request(parameters);
* </code>
*
* #param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* #throws IOException
* if a network error occurs
* #throws MalformedURLException
* if accessing an invalid endpoint
* #throws IllegalArgumentException
* if one of the parameters is not "method"
* #return JSON string representation of the response
*/
public String request(Bundle parameters)
To those who have problems, in the new facebook(); , the string is you App_id, and just delete the APP_ID in the authorized call.
Don't know why the error message is shown, but I guess that facebook updated the facebook SDK.