Post Only text message on facebook from android application - android

sorry for the duplicate question may be but i am really faced problem with Facebook in android application , i want post only message on Facebook wall , i am able to post image with text but i want to post only text please tell me where i am wrong here is my code
This is working code for Image +Text
public void postImageonWall() {
Log.i("Alok", "Test");
Bundle params = new Bundle();
// Inflate Edit text for Facebook Message
params.putString("method", "photos.upload");
params.putString("app_id", mAPP_ID); // I've tried with/without this,
// same result
String message1 = "Test here ";
params.putString("message", message1);
// int r = jj - 1;
//
// Bitmap b = BitmapFactory.decodeFile("/sdcard/D&P post/postimage" + r
// + ".jpg");
// Get image from drawable
Bitmap b = BitmapFactory
.decodeResource(getResources(), R.drawable.test);
Log.i("Bitmap Image is here", "Bitmap" + b);
if (b != null) {
Log.i("Bitmap", "value");
} else {
Log.i("Bitmap", "null");
}
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
if (data != null) {
params.putByteArray("picture", data);
Log.i("final", "value" + message);
params.putString("caption", message);
Log.e("PHOTOUPLOAD", "Attemping an upload...");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
Log.e("PHOTOUPLOAD", "Attemping an upload...");
}
}
Here is Simple click listner :-
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
public void onComplete(String response) {
// TODO Auto-generated method stub
}
public void onIOException(IOException e) {
// TODO Auto-generated method stub
}
public void onFileNotFoundException(FileNotFoundException e) {
// TODO Auto-generated method stub
}
public void onMalformedURLException(MalformedURLException e) {
// TODO Auto-generated method stub
}
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
}
please some one tell me where i made change according to requirement .

Try something like the following.It worked for all my projects,
private void postToFacebook(String review) {
mProgress.setMessage("Posting ...");
mProgress.show();
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("name", title);
params.putString("link", link);
mAsyncFbRunner.request("me/feed", params, "POST",
new WallPostListener());
}
private Handler mRunOnUi = new Handler();
private final class WallPostListener extends BaseRequestListener {
public void onComplete(final String response) {
mRunOnUi.post(new Runnable() {
public void run() {
mProgress.cancel();
Toast.makeText(SVG_View.this,
"Posted to Facebook", Toast.LENGTH_SHORT).show();
}
});
}
}

Try this Method
public void postToWall(String message) {
Bundle params = new Bundle();
params.putString("message", message);
// Uses the Facebook Graph API
try {
facebook.request("/me/feed", params, "POST");
this.finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

how share image on face book in android

Here is the code from which i am able to share data as text format on Share i want share image.
Suppose i have image on sd card please help me how i will share image on face book.
How can i do this ?
Here is my Code :
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String title = "This is facebook Data";
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://m.facebook.com/sharer.php?u="
+ "www.facebook.com" + "&t=" + title + "&_rdr"));
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
});
try this please:
private void fbImageSubmit(Facebook fb, String imageurl, String caption, String description, String name, String linkurl)
{
if(fb != null)
{
if(fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", imageurl);
b.putString("caption",caption);
b.putString("description",description );
b.putString("name",name);
b.putString("link",linkurl);
try {
String strRet = "";
strRet = fb.request("/me/feed",b,"POST");
JSONObject json;
try {
json = Util.parseJson(strRet);
if(!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook","Error: " + strRet);
}
} catch (FacebookError e) {
Log.e("Facebook","Error: " + e.getMessage());
}
} catch (Exception e) {
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}
Try this..
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 postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
And go throuh these Link also:
The easiest way for you is to use the existing SDK, something like that:
http://github.com/facebook/facebook-android-sdk/
http://code.google.com/p/fbconnect-android/
http://wiki.developers.facebook.com/index.php/User:Android
The more flexible way is to implement the API yourself, here are the docs that will be useful:
http://developers.facebook.com/docs/

How to get user name and image using facebook sdk in android app

Integrated facebook sdk to my android app .i can able to successful login now i am Trying to get user id and profile picture and name.but here String jsonUser = fb.request("me"); i am getting facebook error (tried by debugging ,facebookerror catch block executed).how to fix this.
here i am placing code after session valid.
if (fb.isSessionValid()) {
button.setImageResource(R.drawable.logout_button);
pic.setVisibility(ImageView.VISIBLE);
JSONObject obj = null;
URL img_url = null;
try {
String jsonUser = fb.request("me");
obj = Util.parseJson(jsonUser);
String id = obj.optString("id");
String name = obj.optString("name");
hello.setText("Welcome, " + name);
img_url = new URL("http://graph.facebook.com/" + id
+ "/picture?type=normal");
Bitmap bmp = BitmapFactory.decodeStream(img_url
.openConnection().getInputStream());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
button.setImageResource(R.drawable.login_button);
pic.setVisibility(ImageView.INVISIBLE);
}
}
After login call this method...
getProfileInformation();
And after add below codes..
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
// getting email of the user
final String id = profile.getString("id");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email +"\nId: " + id, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state) {
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
public void onFacebookError(FacebookError e, Object state) {
}
});
}
public static AsyncFacebookRunner mAsyncRunner = null;
mAsyncRunner = new AsyncFacebookRunner(fb);

android: I am implement photo post on wall for facebook.when run in Emulator it works fine but not work in device?

I am implement photo post on wall for facebook.when run in Emulator it works fine but not work in device?
Its show on device ERROR: Invalid android_key parameter.The key 3x3UBQp16... does not match any allowed key.Configure your app Key hashes at http://developers.facebook.com/apps/47775390...
I am try to another device but it not work.
Here is my code...
// Facebook
'
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 32665:
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
public void onComplete(Bundle values) {
}
public void onFacebookError(FacebookError e) {
}
public void onError(DialogError e) {
}
public void onCancel() {
}
public class StartFBupdateStatus extends AsyncTask<Void, Void, String> {
private String mFacebookToken;
public StartFBupdateStatus(String mFacebookToken) {
this.mFacebookToken = mFacebookToken;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pDialog = ProgressDialog.show(getParent(), "Please wait...",
"Photo Uploading on Wall", true, true,
new OnCancelListener() {
public void onCancel(DialogInterface pd) {
try {
pDialog.dismiss();
pDialog = null;
taskFBupdateStatus.cancel(true);
} catch (Exception e) {
Log.e("Exception Cought in onCancel:- ",
e.toString());
}
}
});
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, this.mFacebookToken);
// String url = "https://graph.facebook.com/me/photos";
// String url = "https://graph.facebook.com/me/";
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream(
// 32 * 1024);
if (pDetails.image_path != null) {
// byte[] data = null;
// Bitmap bmImg;
// URL myFileUrl = null;
try {
// myFileUrl = new URL(product.image);
// HttpURLConnection conn = (HttpURLConnection)
// myFileUrl
// .openConnection();
// conn.setDoInput(true);
// conn.connect();
// InputStream is = conn.getInputStream();
//
// bmImg = BitmapFactory.decodeStream(is);
//
// bmImg.compress(Bitmap.CompressFormat.PNG, 100, baos);
// data = baos.toByteArray();
// Log.v("SATERRA-FACEBOOK",
// "IMAGE Byte ARRAY SIZE::"+data.length);
bundle.putString("name", product.title);
bundle.putString("picture", pDetails.image_path);
// bundle.putString("message", "icon please");
// bundle.putString("link", "http://www.saterra.com");
// bundle.putString("description",
// product.short_description);
response = facebook.request("me/feed", bundle, "POST");
Log.d("UPDATE RESPONSE", "" + response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
// ********* Over Changes *********
// try {
// baos.close();
// } catch (IOException e1) {
// Log.d("baos error", e1.toString());
// }
if (connMgr.getActiveNetworkInfo() != null
&& connMgr.getActiveNetworkInfo().isAvailable()
&& connMgr.getActiveNetworkInfo().isConnected()) {
try {
// response = Util.openUrl(url, "POST", bundle);
JSONObject json = Util.parseJson(response);
Log.e("Response Photo String", " " + response);
handler.post(new Runnable() {
public void run() {
Toast.makeText(getParent(),
"Photo Uploaded...", Toast.LENGTH_LONG)
.show();
}
});
} catch (Exception e) {
Log.d("Some problem Please try again", e.toString());
}
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getParent(),
"InternetConnectionNotAvailable",
Toast.LENGTH_LONG).show();
}
});
}
} catch (Exception e) {
// Log.e("ProductsDetailActivity",e.getMessage());
Log.e("ProductsDetailActivity", e.toString());
response = null;
}
// String s = facebook.getAccessToken()+"\n";
// s += String.valueOf(facebook.getAccessExpires())+"\n";
// s += "Now:"+String.valueOf(System.currentTimeMillis())+"\n";
return response;
}
#Override
protected void onPostExecute(String result) {
if (result == null) {
Toast toast = Toast.makeText(getParent(), "Facebook Error...",
Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else if (result.indexOf("Duplicate status message") > -1) {
Toast toast = Toast.makeText(getParent(),
"You already said that..", Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else if (result.indexOf("OAuthException") > -1) {
Toast toast = Toast.makeText(getParent(), "Facebook Error...",
Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else {
Toast toast = Toast.makeText(getParent(),
"Facebook update sent", Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
}
pDialog.dismiss();
}
}
private void fbAuthAndPost() {
facebook.authorize(getParent(), new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
Log.d(this.getClass().getName(),
"Facebook.authorize Complete: ");
saveFBToken(facebook.getAccessToken(),
facebook.getAccessExpires());
mFacebookToken = facebook.getAccessToken();
// updateStatus(values.getString(Facebook.TOKEN),
// message);
StartFBupdateStatus taskFBupdateStatus = new StartFBupdateStatus(
mFacebookToken);
taskFBupdateStatus.execute();
}
#Override
public void onFacebookError(FacebookError error) {
Log.d(this.getClass().getName(),
"Facebook.authorize Error: " + error.toString());
}
#Override
public void onError(DialogError e) {
Log.d(this.getClass().getName(),
"Facebook.authorize DialogError: "
+ e.toString());
}
#Override
public void onCancel() {
Log.d(this.getClass().getName(),
"Facebook authorization canceled");
}
});
}
private void saveFBToken(String token, long tokenExpires) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
prefs.edit().putString("FacebookToken", token).commit();
}

Display the posts in facebook application

How Display the posts in facebook application. I tried to work with sample android API for Facebook. But nothing worked fine. I need to display a post that i post on my Facebook wall in android emulator. I need a sample code to run and display the JSON response as my post.
Please send me few working links.
Attach the given code with your facebook login class
public void postOnWall() {
try {
String response = Config.facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", Config.myAccessToken);
parameters.putString("message", "I am Now On FB");
parameters.putString("description", "");
response = Config.facebook.request("me/feed", parameters,
"POST");
if (response == null || response.equals("") ||
response.equals("false")) {
}
} catch(Exception e) {
e.printStackTrace();
}
}
Below is the code and sdk official for facebook on android
https://github.com/facebook/facebook-android-sdk/blob/master/examples/stream/src/com/facebook/stream/StreamHandler.java
public class StreamHandler extends Handler {
private static final String CACHE_FILE = "cache.txt";
/**
* Called by the dispatcher to render the stream page.
*/
public void go() {
dispatcher.getWebView().addJavascriptInterface(
new StreamJsHandler(this), "app");
// first try to load the cached data
try {
String cached = FileIO.read(getActivity(), CACHE_FILE);
if (cached != null) {
JSONObject obj = new JSONObject(cached);
dispatcher.loadData(StreamRenderer.render(obj));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Facebook fb = Session.restore(getActivity()).getFb();
new AsyncFacebookRunner(fb).request("me/home",
new StreamRequestListener());
}
public class StreamRequestListener implements RequestListener {
public void onComplete(String response, final Object state) {
try {
JSONObject obj = Util.parseJson(response);
// try to cache the result
try {
FileIO.write(getActivity(), response, CACHE_FILE);
} catch (IOException e) {
e.printStackTrace();
}
// Convert the result into an HTML string and then load it
// into the WebView in the UI thread.
final String html = StreamRenderer.render(obj);
getActivity().runOnUiThread(new Runnable() {
public void run() {
dispatcher.loadData(html);
}
});
} catch (JSONException e) {
Log.e("stream", "JSON Error:" + e.getMessage());
} catch (FacebookError e) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
}
public void onFacebookError(FacebookError e, final Object state) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("stream", "Resource not found:" + e.getMessage());
}
public void onIOException(IOException e, final Object state) {
Log.e("stream", "Network Error:" + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("stream", "Invalid URL:" + e.getMessage());
}
}
}

android facebook api post to wall with image

I would like to be able to use the facebook android sdk and post a link to facebook. An example of what I want would be is if you were on facebook and you type a link into your status part, like "http://www.google.com". When you do this a box pops up and your post ends up being a block that has an image and a link. I found documentation in the facebook api for this using an attatchment, though when I try to do this with the android facebook api it doesn't seem to work. I've looked for hours on the net, with no luck. Thanks.
Asuming when you read this that you know how to log onto facebook and such via the api...
private void fbImageSubmit(Facebook fb, String imageurl, String caption, String description, String name, String linkurl)
{
if(fb != null)
{
if(fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", imageurl);
b.putString("caption",caption);
b.putString("description",description );
b.putString("name",name);
b.putString("link",linkurl);
try {
String strRet = "";
strRet = fb.request("/me/feed",b,"POST");
JSONObject json;
try {
json = Util.parseJson(strRet);
if(!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook","Error: " + strRet);
}
} catch (FacebookError e) {
Log.e("Facebook","Error: " + e.getMessage());
}
} catch (Exception e) {
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}
This works perfect fine with Progress Dialog box.. I have used it...
You must added the jar of Facebook...
Facebook authenticatedFacebook = new Facebook(APP_ID);
private static final String[] PERMISSIONS = new String[] { "publish_stream", "read_stream", "offline_access" };
Call below function on button Click....
authenticatedFacebook.authorize(YOUR_CLASS_NAME.this, PERMISSIONS, new FaceBookWallPostListener());
Now Add this class...
public class FaceBookWallPostListener implements DialogListener {
public void onComplete(Bundle values) {
new FacebookWallPost().execute();
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class FacebookWallPost extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
path = "Path OF YOUR IMAGE";
Bundle parameters = new Bundle();
parameters.putString("message", "MESSAGE YOU WANT TO POST");
try {
File file = new File(path, "IMAGE_NAME.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
if (data != null) {
parameters.putByteArray("picture", data);
}
parameters.putString("access_token", authenticatedFacebook.getAccessToken());
authenticatedFacebook.request("me");
authenticatedFacebook.request("me/photos", parameters, "POST");
} catch (Exception e) {
return e.getMessage();
}
return "success";
} catch (Exception e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if (result.equals("success")) {
Toast.makeText(YOUR_CLASS_NAME.this, "WallPost Successfully Done", Toast.LENGTH_SHORT).show();
try {
new File(Environment.getExternalStorageDirectory().toString() + "/Diegodeals", "diegodeals.jpg").delete();
} catch (Exception e) {
}
} else {
Toast.makeText(YOUR_CLASS_NAME.this, "Failed to post \n " + result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(YOUR_CLASS_NAME.this);
pDialog.setMessage("Posting Picture & Message on Facebook...");
pDialog.show();
}
}
/////GOOOD LUCK.

Categories

Resources