facebook sdk android wall post line break - android

I'm making an application that is posting some information to your facebook wall using facebook sdk for android. This works, but I can't seem to get new lines on the posts. I have tried \n but it doesent work. Any suggestions?
Here is my code:
Bundle parameters = new Bundle();
String temp = "";
for (int i = 0; i < mArrayAdapter.getCount(); i++){
temp = temp + mArrayAdapter.getItem(i) + "\n"; // Not working
}
parameters.putString("message", temp);
mFacebook.dialog(this, "stream.publish", parameters, new DialogListener());
Thanks,
James Ford

Hi James i have tried that before, even with html code but i think thats not possible.
The reason, Facebook must have a control to avoid blank spaces or line break on his posts.

New lines are not allowed in stream posts (the fact that you may have seen them in the past are bugs on facebook).

make use of JSON to post on facebook..
how? look here
STEPS :-
Step 1 :- At this link u will came to know how to use JSON for setting text to TEXTVIEW.
Step 2 :- May be this is not u r looking for :) assign the text of textview to some string
using GetText().ToString
Step 3 :- use this string to post to the facebook.
Step 4 :- I did the same after spending lot of time in googling and finally got the result
by using this trick. u can see my post that i posted during test here
Step 5 :- set the visibilty of this text box to gone using
tv.setVisibility(View.GONE)
And u r done with your posting to facebook..
let the facebook and textview handle how they manage spaces and new line character :D
Some Coding work for newbies like me...
I am posting it on click of button
1)
tv= (TextView)findViewById(R.id.tv);
click=(Button)findViewById(R.id.btn1);
click.setOnClickListener(mthdpost);
2) add on click event to this button
private View.OnClickListener mthdpost=new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String json = "{"
+ " \"name\": \"myName\", "
+ " \"message\": [\"myMessage1\",\"myMessage2\"],"
+ " \"place\": \"myPlace\", "
+ " \"date\": \"thisDate\" "
+ "}";
/* Create a JSON object and parse the required values */
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String name = object.getString("name");
String place = object.getString("place");
String date = object.getString("date");
JSONArray message = object.getJSONArray("message");
String MessageToPost= null;
tv.setText("Name: "+ name +"\n\n");
tv.append("Place: "+ place +"\n\n");
tv.append("Date: "+ date +"\n\n");
/*JSONObject attachment = new JSONObject();
attachment.put("Name: ","\n\n");
attachment.put("Place: ","\n\n");
attachment.put("Date: ","\n\n");*/
for(int i=0;i<message.length();i++)
{
tv.append("Message: "+ message.getString(i) +"\n\n");
//attachment.put("Message: ","\n\n");
}
MessageToPost=tv.getText().toString();
postToWall(MessageToPost);// called the method having logic to post on wall and sending the textview text to to post as message
} catch (JSONException e)
{e.printStackTrace();
}
catch(Exception ex)
{ex.printStackTrace();}
}
};
3) method for posting the message
public void postToWall(String msg){
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
//parameters.putString("message", msg.toString());
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();
}
}
HOPE IT WILL HELP :)

This worked for me:
StringBuilder messageData = new StringBuilder(title).append('\n')
.append('\n').append(message).append('\n').append('\n')
.append(description);
// Message
postParams.putString("message", messageData.toString());

This works:
Use this: <center></center>
Instead of a br or a newline, etc. You can only do one in a row (ie. you can't increase the spacing).

Related

How can show textview when result not empty in android?

I'm new to android development. I know this one may repeated question but I didn't understood how i implement these methods. I want to show TextView when result not empty, I have researched and find some method like textview.setVisibility(View.INVISIBLE); OR textview.setVisibility(View.GONE); I'm trying so far but did not get any result.
I have tried this but it is not working properly. Please guide me where i'm wrong.
String Msg = json1.getString("msg");
resultView.setText("Error :" + Msg);
resultView.setVisibility(View.GONE);
Try this
String str = json1.getString("msg");
if (!str.isEmpty()) {
rersultView.setVisibility(View.VISIBLE);
resultView.setText("Error :" + Msg);
} else {
rersultView.setVisibility(View.GONE);
}
Similiar to ULHAS answer, but You can do also:
String jsonString = json1.getString("msg");
if(!jsonString.isEmpty()){
rersultView.setVisibility(View.VISIBLE);
resultView.setText("Error :" + Msg);
}else{
rersultView.setVisibility(View.GONE);
}
I think you have to do something like these:
if(Msg.equalsIgnoreCase("")) { // OR if(Msg.equals(""))
resultView.setVisibility(View.GONE);
} else{
resultView.setVisibility(View.VISIBLE);
resultView.setText("Error :" + Msg);
}
Try it may help you.

implement facebook like button

I created an android app to show comments of certain post from facebook.
what I want to do is to implement the like button.
I have all the necessary data (facebook token, user id, app id etc.) and permission i need from the user.
circle number 1 is the content of the comment
circle number 2 is the name if the user
circle number 3 is the like button that i want to implement
circle number 4 is the time that the comment sent
I use this link to get the comments:
https://graph.facebook.com/568609876496765/comments
it returns a JSON Object that i phrase and get the data and show it in a List View.
Thanks in advance.
Unlike webpages, you cannot add a Facebook Like button to an Android app. However, you can add the function to Like a post (a Comment in your case) by using "POST" or a "DELETE" query to the Facebook API:
Here is a complete functioning example of what I do to Toggle the Like Status of a Comment in my application:
NOTE: This code is for the older v2.x SDK. So you will need to adapt a few things that are specific to the latest v3.x SDK
On the onClickListener you will use to post / remove a Like, run this piece of code:
try {
String query = "SELECT user_likes FROM comment WHERE post_id= \'"
+ THE_COMMENT_ID + "\'";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
String fqlResponse = Utility.mFacebook.request(params);
JSONArray JALikes = new JSONArray(fqlResponse);
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
if (JOTemp.has("user_likes")) {
String userLikeStatus = JOTemp.getString("user_likes");
if (userLikeStatus.equals("true")) {
try {
Bundle parameters = new Bundle();
Utility.mFacebook.request(arrayComments.get(position).getCommentID() + "/likes", parameters, "DELETE");
// CHANGE THE TEXT OF THE WIDGET TO SHOW THE TOGGLED STATE
}
catch(Exception e) {
e.printStackTrace();
}
} else if (userLikeStatus.equals("false")) {
try {
Bundle parameters = new Bundle();
Utility.mFacebook.request(arrayComments.get(position).getCommentID() + "/likes", parameters, "POST");
// CHANGE THE TEXT OF THE WIDGET TO SHOW THE TOGGLED STATE
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
In the first part of the code (before the for loop), I check the current status if the Logged in user likes the Comment. Based on the result (in the for loop), I either remove the Like or I post a Like.
Although it is an older SDK, the code is still valid, and with a few modifications (if necessary) will work just fine.

How to post a message on facebook friends wall in Android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Facebook post on Friends wall in Android
I have made an app in which i am fetching list of my all FACEBOOK friends, now i want while i do click on any of the friend row then i will be able to post on his/her wall.
So what are the permissions i need to give and what type of code i need to write to do that,
Like: still i have given below permission and written below code onListItemClick
permissions :
mFacebook.authorize(main, new String[] { "publish_stream",
"friends_birthday", "friends_photos" }, new MyAuthorizeListener());
Code:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
}
I am fetching FbId, name, bday and picture
public class MyFriend {
private String fbID = " ";
private String name = " ";
private String bday = " ";
private String pic = " ";
}
Now on-wards you can not post to our friend's wall.
Because Facebook has removed the feature from its Graph Api, so that we cannot Post on Friend's Wall
thats why we can only post on our facebook wall only.
Feature of posting on friend's wall has been removed from the Facebook sdk.
Previously it could have been done by the following code as claimed by this post,
try{
Bundle parameters = new Bundle();
JSONObject attachment = new JSONObject();
try {
attachment.put("message", "Messages");
attachment.put("name", "Get utellit to send messages like this!");
attachment.put("href", link);
} catch (JSONException e) {
}
parameters.putString("attachment", attachment.toString());
parameters.putString("message", "Text is lame. Listen up:");
parameters.putString("target_id", "XXXXX"); // target Id in which you need to Post
parameters.putString("method", "stream.publish");
String response = authenticatedFacebook.request(parameters);
Log.v("response", response);
}
catch(Exception e){}

Android FQL Call Returning Empty after Successful Calls [Title Changed]

Ok Here's my problem.
I am making an FQL query and I am storing the response data. My code runs fine, except after about 4 minutes of the app running I get a JSONException. The Exception reads
A JSONArray text must start with '[' at character 0 of
Which is strange, because if I type in the URL the query is making into a browser I get the following
[{"uid":SOMENUMBER},{"uid":SOMENUMBER}]
Which clearly begins with the "[" character.
Here's the request
String query = "SELECT uid FROM user WHERE is_app_user=1 and uid IN (SELECT uid2 FROM friend WHERE uid1 =" + fbId + ")";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
mAsyncFacebookRunner.request(null, params, new FQLRequestListener());
Here's the RequestListener
private class FQLRequestListener implements RequestListener
{
#Override
public void onComplete(String response, Object state)
{
try {
JSONArray json = new JSONArray(response);
friendsIds = new ArrayList<String>();
for(int i = 0; i < json.length(); ++i)
{
String uid = json.getJSONObject(i).getString("uid");
friendsIds.add(uid);
Log.d("friends", friendsIds.get(i));
}
InviteFriends.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
setUpList();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
And the Stack..
06-15 16:43:21.744: D/Facebook-Util(866): GET URL: THIS IS THE URL THAT WORKS IN A BROSWER (actual URL removed)
06-15 16:43:21.774: W/System.err(866): org.json.JSONException: A JSONArray text must start with '[' at character 0 of
06-15 16:43:21.774: W/System.err(866): at org.json.JSONTokener.syntaxError(JSONTokener.java:448)
06-15 16:43:21.774: W/System.err(866): at org.json.JSONArray.<init>(JSONArray.java:104)
06-15 16:43:21.774: W/System.err(866): at org.json.JSONArray.<init>(JSONArray.java:150)
06-15 16:43:21.774: W/System.err(866): at rageup.android.InviteFriends$FQLRequestListener.onComplete(InviteFriends.java:129)
06-15 16:43:21.774: W/System.err(866): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:254)
I should note that..
Query works when I logout and log back in.
I have ensured my Facebook session is valid.
The Facebook provided "Hackbook" example has the same problem when downloading a friend's list.
Flow of Getting the Exception
Home Page Where User Logs In
User Clicks a Button to Start Second Activity
Second Activity is Where Query is Made
Return Home
Repeat after about 4 minutes, minus the login
First try to validate the response.
I would use:
JSONObject json = new JSONObject(response);
It gives you an opportunity to check the content of the json object using it's methods. You can't assume, that facebook api will always respond expected form of data.
You can do:
Log.w("FacebookListener", "Unexpected response: " + response);
And then inspect Logcat output.
OK. I haven't tested it yet, but according to: http://developers.facebook.com/docs/reference/rest/fql.query/ the graph path for fql queries is "fql"
In mAsyncFacebookRunner.request(null, params, new FQLRequestListener()); you pass null, but "fql" is probably expected
EDIT
I have checked it on graphapi explorer - it works, when "query" is replaced by simple "q".
Make sure, you are authenticated within your app (Single sign on, or OAuth dialog)
Bundle params = new Bundle();
params.putString("q", query);
mAsyncFacebookRunner.request("fql", params, new FQLRequestListener());
Another EDIT:
While working on different project, I have noticed, that there may be a problem with Facebook Util class's method "read" - sometimes (even if InputStream had data) BufferedReader returned null, and broke loop. I have changed body of the method into:
private static String read(InputStream in) throws IOException {
StringBuffer sb = new StringBuffer();
final InputStreamReader rd = new InputStreamReader(in);
try {
final char[] buffer = new char[1024];
int read;
while((read = rd.read(buffer)) != -1){
sb.append(buffer, 0, read);
}
} catch (Exception e) {
} finally {
try {
rd.close();
} catch (Exception e2) {
}
}
return sb.toString();
}
and it worked.
I have the exact same problem:
calling the fql (simple fql call, not asyncfqlrunner) I have no problems at all. If I wait a few minutes (2-4) and try again sending an fql request, I get an exception by the facebook android api:
A JSONObject text must begin with '{' at character 0 of
I also have ensured that the fb session is valid und the query is correct. nothing has changed, except the time of excecution.
I tried the approche to rewrite the
private static String read(InputStream in) throws IOException method but the error still occurs.
EDIT
Since even facebook isn't aware of this problem and nobody else has posted anything about this I have figured it out by myself. When using the normal request-method (not the async one), go to the Facebook.java in the FB-API and change the following line under in
the public String request(Bundle parameters):
FROM:
return request(null, parameters, "GET");
TO
return request(null, parameters, "POST");
and everything should work fine!

Creating a custom Wall Post with Facebook API on Android

I'm new to Facebook API on Android, and basically, what I'm trying to do is creating custom wall post for an application I'm developing.
Like when you listen a Shazam a song and you can share the result with your friends.
I believe I've got to create a custom attachment. Here's my code for setting the attachment:
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle myParams = new Bundle();
String attachment="{\"name\":\"Gran Turismo 5\"," +
"\"href\":\"http://www.unknown.com/?lang=fr\"," +
"\"caption\":\"Sony Computer Entertainment\",\"description\":" +
"\"Une vidéo proposée par Cedemo.\",\"media\":" +
"[{\"type\":\"image\",\"src\":" +
"\"http://www.unknown.com/prepicture//thumb_title/15/15061_1.jpg\"," +
"\"href\":\"http://www.unknown.com/?lang=fr\"}],\"properties\":" +
"{\"Autre lien\":{\"text\":\"Cedemo\",\"href\":\"http://www.unknown.com\"}}}";
myParams.putString("attachment", URLEncoder.encode(attachment);
mFacebook.dialog(Option.this, "stream.publish",myParams,
new SampleDialogListener());
And then, later on:
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId,values, new WallPostRequestListener());
} else {
Log.d("Facebook-Example", "No wall post made");
}
}
}
I didn't wrote the attachment String, It's just a test taken from another question made in this forum. Anyway, when I call myAsync.request, my app shows an error message, how am I supposed to pass the attachment to my dialog?
Hope I've been clear enough.
Are you sure you need to set custom parameters? It sounds like you can just want to post a Facebook message directly to the wall: you can do this by simply handing in the message parameter as a string -- you only need all that JSON if you want to attach an image etc. And note on facebook's page it says using this api call won't post a status update that others can see on their feed, it will just appear on their own wall. If you just want to post a message with a link you should just be able to use your mAsyncRunner (once you have your valid Facebook session) using this:
String message = "Post this to my wall";
Bundle parameters = new Bundle();
parameters.putString("message", message);
mAsyncRunner.request("me/feed", parameters, "POST", new WallPostRequestListener());
Also may help if you posted the error/response code you're getting from Facebook.

Categories

Resources