Retrieving Facebook Profile Picture - java

My graphrequest seems to work fine, I have no issue retrieving the User who logs ins Name nor do I have any problem getting their ID. I am trying to store their profile picture for use within my app (By downloading it as a bitmap) but cant seem to succesfully download it. Could someone tell me what I am doing wrong?
//Run the first time we log into Facebook
//connects everything here
private void firstTimeFBlogin() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.i("joe", "Heyyyyo");
try {
String userName = response.getJSONObject().getString("name");
String userID = response.getJSONObject().getString("id");
//String hi2 = response.getJSONObject().getString("first_name");
//String hi3 = response.getJSONObject().getString("gender");
final JSONObject mPicture = object.getJSONObject("picture");
final JSONObject mPictureData = mPicture.getJSONObject("data");
final String mImageUrl = mPictureData.getString("url");
Log.i("joe", "User's Facebook Name: " + userName);
Log.i("joe", ParseUser.getCurrentUser().getUsername());
Log.i("joe", mImageUrl);
Log.i("joe", userID);
ParseUser.getCurrentUser().put("name", userName);
ParseUser.getCurrentUser().put("iUrl", mImageUrl);
ParseUser.getCurrentUser().put("fbID", userID);
ParseUser.getCurrentUser().saveInBackground();
profilePictureRetriever(userID);
} catch (JSONException e) {
Log.i("joe", "Couldn't Succesfully retrieve the stuff...");
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,picture");
request.setParameters(parameters);
request.executeAsync();
}
public void profilePictureRetriever(String id) {
Log.i("joe", "Profile Picture Checker");
//Bitmap bitmap = getFacebookProfilePicture(id);
//this is here for test purposes
//tried just maually putting the url in..
Bitmap bm = DownloadImageBitmap("https://graph.facebook.com/849993771766163/picture?type=square");
}
public static Bitmap DownloadImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("IMAGE", "Error getting bitmap", e);
}
return bm;
}
}
Is there another/better way to be doing this?
Thanks so much!

I have done something like this:
First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.
Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
JSONObject data = response.getJSONObject();
if (data.has("picture")) {
String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
Bitmap profilePic = getFacebookProfilePicture(profilePicUrl);
// set profilePic bitmap to imageview
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
You can use this method which returns current Profile picture of User from URL which we get from above GraphRequest API.
public static Bitmap getFacebookProfilePicture(String url){
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bitmap;
}
I hope it helps!

Update
Pass required parameter in bundle, as id,name,email,gender, birthday,picture is passed in below code.
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.e(TAG, "Cancel");
}
#Override
public void onError(FacebookException exception) {
Log.e(TAG, "Error");
Log.e(TAG, exception.toString());
}
});
Old Answer
get it by calling
graph.facebook.com/<FB UserId>/picture?type=large

following code is put after login success.
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
Log.d("info",object.toString()+"");
String id = object.getString("id");
String profilePic ="http://graph.facebook.com/"+id+"/picture";
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,age_range,gender,locale,timezone,updated_time,verified,email");
request.setParameters(parameters);
request.executeAsync();

Related

Can't get Facebook ID and email

I faced with the following problem: I need to get FB id and email after authorization. Here's my code:
#Override
public void onSuccess(LoginResult loginResult) {
final String[] email = new String[1];
final String[] id = new String[1];
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email");
request.setParameters(parameters);
request.executeAsync();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
bundle.putString(EXTRA_EMAIL, email[0]);
bundle.putString(EXTRA_ID, id[0]);
mPresenter.saveUserData(bundle);
}
But when I run my app, I don't get this fields. I checked in debugger and part
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?
UPD
Probably, maybe it would help, here's whole fb logic:
mCallbackManager = CallbackManager.Factory.create();
mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final String[] email = new String[1];
final String[] id = new String[1];
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email");
request.setParameters(parameters);
request.executeAsync();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
bundle.putString(EXTRA_EMAIL, email[0]);
bundle.putString(EXTRA_ID, id[0]);
mPresenter.saveUserData(bundle);
}
UPD 2
I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?
UPD 3
I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
if (response.getJSONObject() != null) {
JSONObject data = response.getJSONObject();
if (data.has(FB_EMAIL_PERMISSION)) {
email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
}
if (data.has(FB_ID_PERMISSION)) {
id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
And here's the values of permissions:
private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";
did you add permission to your facebook login button
fbLoginButton.setPermissions(Arrays.asList("public_profile,email,user_birthday"));
this is how i am using it
i am not sure of the value of FB_EMAIL_PERMISSION FB_ID_PERMISSION
final GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String id = "", user_email = "", name = "";
Log.d("EHREIUIU", String.valueOf(object));
if (response.getJSONObject() != null) {
JSONObject data = response.getJSONObject();
if (data.has("id"))
id = data.getString("id");
if (data.has("email"))
user_email = data.getString("email");
}
getOneSignalToken();
socialLogin(user_email, name, null, id, "facebook");
} catch (JSONException e) {
e.printStackTrace();
}
}
});

How to get the share(Post) photo URl or link with facebook SDk?

I want to take Url of Facebook post image. I am successfully posting the photo on Facebook with the logInWithPublishPermissions but I want the link or Url of the post image in call back....
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("VodaFone Rakshavandhan!")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareDialog shareDialog = new ShareDialog(FacebookShareActivity.this);
shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.e("###result", String.valueOf(result));
/* "/"+mFBID+"_"+postid+"?fields=link,message",*/
String postid=result.getPostId().toString();
mUrlFb="https://www.facebook.com/photo.php?fbid="+postid;
Log.e("###mUrlFb",mUrlFb);
GraphRequest request = new GraphRequest(
accessToken,
"/"+mFBID+"_"+postid,
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("##response", String.valueOf(response));
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,link,message");
request.setParameters(parameters);
request.executeAsync();
/* new GraphRequest(
AccessToken.getCurrentAccessToken(),
result.getPostId(),
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("##response", String.valueOf(response));
}
}
).executeAsync();*/
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
e.printStackTrace();
}
});
I am getting the Response from this Graph Request
{Response: responseCode: 200, graphObject:
{"id":"104752556880730_105851436770842"}, error: null}
any help appreciate.
Special Thanks to #CBroe
Only Add the parameter **permalink_url**
parameters.putString("fields", "id,link,message,permalink_url");

UI does not update after Face Book request...why?

I am trying to set text in TextView userEmail, after calling FaceBook request for getting Email.
public TextView userEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
//user_profile_name
userName = (TextView)findViewById(R.id.user_profile_name);
userEmail = (TextView)findViewById(R.id.user_profile_short_bio);
userbday = (TextView) findViewById(R.id.user_bday);
getMyFBProfileRequest();
}
public void getMyFBProfileRequest() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response",response.toString());
Toast.makeText(MyProfileActivity.this,object.getString("email") ,
Toast.LENGTH_SHORT).show();
// Application code
String email = object.getString("email");
String birthday = object.getString("birthday");
userEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
Log.i("Error","");
//profileView.showToast("Error");
}
}
});
// GraphRequest.GraphJSONObjectCallback objectCallback = new JSONObjectCallback();
// GraphRequest request = GraphRequest.newMeRequest(accessToken, objectCallback);
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
And I get a fine response, which I see in toast.
But nothing change in textView. UI does not update… why? I do not know what to do. I used Broadcast Receiver. lost a lot of time. It does not work… Help me, please, anybody.
FB answer has field "birthday"! But my request did't get birthday. It is correct for get it: params.putString("fields", "birthday")
params.putString("fields","email,birthday,picture.type(large)");
2) To surround with try catch all operation with JSONObject:
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}
and set "" in cath if result null;
So, now my request looks like:
Bundle params = new Bundle();
params.putString("fields", "email,birthday,picture.type(large)");
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/", params, HttpMethod.GET,
new GraphRequest.Callback() {
public ImageLoader imageLoader;
public ImageView mImageView;
public UserInfo userModel;
#Override
public void onCompleted( GraphResponse response) {
saveDataInSingletone(response);
profileView.setInfoToView();
}
private void saveDataInSingletone(GraphResponse response) {
JSONObject data = response.getJSONObject();
userModel = UserInfo.getInstance();
String lastName, firstName;
String profilePicUrl;
if (data.has("picture")) {
try {
profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
// getFacebookProfilePicture(profilePicUrl);
// imageView = (ImageView) findViewById(R.id.pic);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
userModel.setAvatar(profilePicUrl);
//mImageView.setImageBitmap(profilePic);
// userModel.setAvatar(profilePic);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}}).executeAsync();

Failed to send image from one activity to another. Please see details

I'm fetching user's profile picture from facebook and I want to send it to ProfileActivity.java so that it can be displayed on user profile.
The problem is that the image is not getting sent from SignUpScreen.java to ProfileActivity.java. Though I am able to send name & email from one to another.
Here's SignUpScreen.java file's code:
public class SignUpScreen extends AppCompatActivity {
Button facebookLoginButton;
CircleImageView mProfileImage;
TextView mUsername, mEmailID;
Profile mFbProfile;
ParseUser user;
Bitmap bmp = null;
public String name, email, userID;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_sign_up_screen);
TextView textView = (TextView) findViewById(R.id.h);
Typeface typeface = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/Pac.ttf");
textView.setTypeface(typeface);
mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
mUsername = (TextView) findViewById(R.id.userName);
mEmailID = (TextView) findViewById(R.id.aboutUser);
mFbProfile = Profile.getCurrentProfile();
//mUsername.setVisibility(View.INVISIBLE);
//mEmailID.setVisibility(View.INVISIBLE);
facebookLoginButton = (Button) findViewById(R.id.facebook_login_button);
facebookLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpScreen.this, mPermissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
getUserDetailsFromFacebook();
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
saveNewUser();
}
}, 5000);
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
});
}
public void saveNewUser() {
user = new ParseUser();
user.setUsername(name);
user.setEmail(email);
user.setPassword("hidden");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(SignUpScreen.this, "SignUp Succesful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SignUpScreen.this, "SignUp Unsuccesful", Toast.LENGTH_LONG).show();
Log.d("error when signingup", e.toString());
}
}
});
}
private void getUserDetailsFromFacebook() {
final GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
//Log.d("response", "response" + object.toString());
Intent profileIntent = new Intent(SignUpScreen.this, ProfileActivity.class);
Bundle b = new Bundle();
try {
name = response.getJSONObject().getString("name");
mUsername.setText(name);
email = response.getJSONObject().getString("email");
mEmailID.setText(email);
userID = response.getJSONObject().getString("id");
new ProfilePicAsync().execute(userID);
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
profileIntent.putExtra("user_pic", bmp);
startActivity(profileIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
class ProfilePicAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String imageURL;
String id = userID;
imageURL = "https://graph.facebook.com/"+ id +"/picture?type=large";
try {
bmp = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
e.printStackTrace();
Log.d("Loading picture failed", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mProfileImage.setImageBitmap(bmp);
}
}
}
Here's ProfileActivity.java file's code:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
CircleImageView mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
TextView mUsername = (TextView) findViewById(R.id.userName);
TextView mEmailID = (TextView) findViewById(R.id.aboutUser);
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("user_pic");
mProfileImage.setImageBitmap(bitmap);
mUsername.setText(bundle.getString("userName"));
mEmailID.setText(bundle.getString("userEmail"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Please let me know what is going wrong here.
In your getUserDetailsFromFacebook() method you have called new ProfilePicAsync().execute(userID) to get the image. But it seems that before you could fetch the image ,startActivity(profileIntent) probably gets called.
First be sure that you have fetched the image from facebook before you call startActivity(profileIntent).
EDIT
Add this to your getUserDetailsFromFacebook() ,
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
profileIntent.putExtra("user_pic", byteArray);
startActivity(profileIntent);
Add this to your ProfileActivity.java ,
byte[] byteArray = getIntent().getByteArrayExtra("user_pic");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mProfileImage.setImageBitmap(bmp);
This is not a right way to pass image from Activity to Activity within same application. You can easily send the path by intent and load it into other Activity.
To save a bitmap in Activity A, use
FileOutputStream out = null;
try {
out = new FileOutputStream(FILENAME); //FILENAME is your defined place to store image
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Now you have FILENAME global string which is accessible from Activity B.
Just load it where its needed.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(FILENAME, options);
mProfileImage.setImageBitmap(bitmap);
it works for me.
OneActivity.java
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(StartPage.this, SecondActivity.class);
Toast.makeText(StartPage.this, "You have setted this wallpaper for Monday", Toast.LENGTH_LONG).show();
intent.putExtra("pic", byteArray);
//intent.putExtra("resourseInt", bm);
startActivity(intent);
SecondActivity.Java
byte[] byteArray;
Bitmap bmp,
byteArray = getIntent().getByteArrayExtra("pic");
bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
myWallpaperManager.setBitmap(bmp);

Android post picture to Facebook wall

I am trying to post a picture to my wall on Facebook. I have managed logging in and posting text to the wall. However, when I try posting the picture, nothing happens.
I am using the Android Facebook SDK.
Here is what I have so far:
Bundle params = new Bundle();
params.putString("method", "photos.upload");
Toast.makeText(FacebookPoster.this, "" + getIntent().getExtras().getByteArray("data").length, Toast.LENGTH_SHORT).show();
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
The Toast shows 8733, which means the byte array isn't empty
NB. Logcat output some warnings (not errors):
03-02 14:19:29.554: WARN/Bundle(1891): Attempt to cast generated internal exception:
03-02 14:19:29.554: WARN/Bundle(1891): java.lang.ClassCastException: java.lang.String
03-02 14:19:29.554: WARN/Bundle(1891): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Util.openUrl(Util.java:155)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)
03-02 14:19:29.584: WARN/Bundle(1891): Key method expected byte[] but value was a java.lang.String. The default value <null> was returned.
(Shows several times underneath each other.)
What am I doing wrong?
SOLVED.
This is what I did to make it work:
facebook.authorize(this, new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError dialogError) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
postToWall(values.getString(Facebook.TOKEN));
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
And the helper method:
private void postToWall(String accessToken) {
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
// The byte array is the data of a picture.
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException fileNotFoundException) {
makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
makeToast(ioException.getMessage());
}
}
first thing is that you are not using graph api to upload the pictures... u r using the old rest api... try to use graph api, its simple...
Use following code:
Bundle param = new Bundle();
param.putString("message", "picture caption");
param.putByteArray("picture", ImageBytes);
mAsyncRunner.request("me/photos", param, "POST", new SampleUploadListener());
According to error message, it looks like its giving errors in getting bytes from intent's bundle...
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 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) {
}
}
try this code it will work i had used the same code and uploads the image on Facebook.
Here is the working code sample. Pass image path and message.
public static void postImageonWall(String FilePath,String msg ) {
try {
Bitmap bi = BitmapFactory.decodeFile(FilePath);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", msg);
param.putString("filename", "Dessert Dash");
param.putByteArray("image", byteArray);
param.putString("caption", "Dessert Dash in Android Market Now");
mAsyncRunner.request("me/photos", param, "POST", fbrq, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String postwall(String uid)
{
String response = "";
try
{
String DIRECTORY_PATH = "/sdcard/159.jpg";
Bundle params = new Bundle();
Bitmap bitmap = BitmapFactory.decodeFile(DIRECTORY_PATH);
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
params.putString("app_id", uid);
params.putString("message", "picture caption");
params.putByteArray("picture", data);
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
mAsyncRunner.request("me/photos", params, "POST", new WallPostRequestListener());
mAsyncRunner.request(response, new WallPostRequestListener());
Log.e("post result", response);
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
public class WallPostRequestListener extends BaseRequestListener
{
public void onComplete(final String response)
{
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try
{
JSONObject json = Util.parseJson(response);
message = json.getString("message");
}
catch (JSONException e)
{
Log.w("Facebook-Example", "JSON Error in response");
}
catch (FacebookError e)
{
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
}
}
I'm sure Facebook will fix this eventually, but for the time being these examples (posted by other users) are very misleading because they do NOT in fact post to the user's wall (in the regular sense). Instead they are added to the user's photo gallery, and then happen to end up on the wall, but not in the same way in which normal posts work... there is no title and no caption and if you add another photo it ends up side by side with the first (rather than as a separate entry). So, when you use the api command me/feed it just fails in a spectacular way where it actually adds a post to the wall but it's an empty post from the application (it even disregards the title and caption).
Hopefully Facebook will fix this sometime in the near term.
Posting the image and Text to Facebook wall from code, Once you logged in using facebook credentials.
note : This is applicable only after logging in to your app using facebook credentials
sharePhotoToFacebook(); //function called from any UI event
private void sharePhotoToFacebook(){
Bitmap bitmap=null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/";
try {
File file = new File(path, "image9.jpg");
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
catch (Exception e){
Log.e("Error" , " Error in loading file");
}
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("A post from Android code")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
Toast.makeText(LoginSuccessActivity.this, "Image posted successfully", Toast.LENGTH_LONG).show();
}

Categories