Display the posts in facebook application - android

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());
}
}
}

Related

Not able to upload the audio file along with the data to the server through nougat version of android

I'm not able to upload the audio file to the server through the nougat version of android, The audio is recorded through the media recorder and saved on the device.Here is the code, the same is working for all the versions of android except nogat ,though in nogat the media is recorded and saved in device , but it not being uploaded on the server.
private void submitRecording() {
CallLogsModel.idle++;
final String filename = "file.MP3";
final String path = Environment.getExternalStorageDirectory() + "/" + filename;
JSONObject jObject = new JSONObject();
String json = "";
try {
String uniquecode = PreferenceConfigration.getPreference(Constants.PreferenceConstants.UNIQUE_CODE);
String token= UtilityMethods.tokenValue();
Log.e("Token",token);
jObject.put("uniquecode",uniquecode);
jObject.put("lead_id", CallLogsModel.leads);
jObject.put("duration",getAudioDuratiion());
jObject.put("date_of_call", getDate());
jObject.put("time_of_call",startTime);
jObject.put("device", PreferenceConfigration.getPreference(Constants.PreferenceConstants.DEVICE).toString());
jObject.put("token", token);
Log.e("formed",jObject.toString());
if (path.equals("") || path.equals(null) || path.equals("null")) {
jObject.put("aboutphoto", "nophoto");
}
else
{
}
json = jObject.toString();
} catch (Exception e) {
}
Log.e("raisetic", json);
OKhttpConnect.doPosttRequestWithMutipart("all_data", "attachment", "http://armsenterprise.com/api-new/kre-app/save_call_log.php", json, Environment.getExternalStorageDirectory() + "/" + filename, new HTTPcallback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("Failure",e.toString());
}
#Override
public void onResponse(final String response) {
if (response != null && !(response.isEmpty())) {
final JSONObject jsonObject;
try
{
CallLogsModel.idle++;
jsonObject = new JSONObject(response);
Log.e("ResponseCall", response);
} catch (Exception e)
{
e.printStackTrace();
}
} else {
((Activity) MainActivity.context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Error in submission", Toast.LENGTH_SHORT).show();
}
});
}
}
});
((Activity) MainActivity.context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.context, "Raising Ticket ...", Toast.LENGTH_SHORT).show();
}
});
}

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/

Post Only text message on facebook from android application

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();
}
}

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 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