I use the official Facebook SDK in my Android Application. After the user logs in, I can get the uid and the name of the facebook user like so:
Facebook mFacebook = new Facebook(APP_ID);
// ... user logs in ...
//String jsonUser = mFacebook.request("me/picture"); // throws error
String jsonUser = mFacebook.request("me");
JSONObject obj = Util.parseJson(jsonUser);
String facebookId = obj.optString("id");
String name = obj.optString("name");
I also know that the I can access the profile picture with those links:
https://graph.facebook.com/<facebookId>/picture
https://graph.facebook.com/<facebookId>/picture?type=large
I would love to use this code to geht the profile picture:
public static Drawable getPictureForFacebookId(String facebookId) {
Drawable picture = null;
InputStream inputStream = null;
try {
inputStream = new URL("https://graph.facebook.com/" + facebookId + "/picture").openStream();
} catch (Exception e) {
e.printStackTrace();
return null;
}
picture = Drawable.createFromStream(inputStream, "facebook-pictures");
return picture;
}
But it just wont work. I always get the following error:
SSL handshake failure: Failure in SSL library, usually a protocol error
And I cant solve this issue. It seems to be rather complicated(look here or here). So what other options are there to get the picture of a facebook user that successfully logged into my application?
ImageView user_picture;
userpicture=(ImageView)findViewById(R.id.userpicture);
URL img_value = null;
img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
userpicture.setImageBitmap(mIcon1);
where ID is ur profile ID...
I also had that problem some time ago. What I did was download the picture using an async task, and then set an ImageView with the image just downloaded. I will paste the code snippet:
ImageView fbUserAvatar = (ImageView) findViewById(R.id.fb_user_avatar);
private synchronized void downloadAvatar() {
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
#Override
public Bitmap doInBackground(Void... params) {
URL fbAvatarUrl = null;
Bitmap fbAvatarBitmap = null;
try {
fbAvatarUrl = new URL("http://graph.facebook.com/"+USER_ID+"/picture");
fbAvatarBitmap = BitmapFactory.decodeStream(fbAvatarUrl.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fbAvatarBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
fbUserAvatar.setImageBitmap(result);
}
};
task.execute();
}
This code works for me. I hope it works for you too.
You can request a direct URl which contains your Access token:
URL MyProfilePicURL = new URL("https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="+ Access_token );
Then get a decoded BitMap and assign it to image view:
Bitmap MyprofPicBitMap = null;
try {
MyprofPicBitMap = BitmapFactory.decodeStream(MyProfilePicURL.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MyProfilePicImageView.setImageBitmap(mIcon1);
request("me/picture") throws an error because the server returns a 302 (redirect to the image url) and the facebook sdk does not handle this.
For displaying profile pic in your app, use ProfilePictureView from Facebook SDK.
Refer This
Just call setProfileId(String profileId) on it.
It will take care of displaying the image.
Add one line of code and that will be resolved.
HttpURLConnection.setFollowRedirects(true);
Use this, (usuario is a GraphUser):
ProfilePictureView p;
p = (ProfilePictureView) rootView.findViewById(R.id.fotoPerfil);
p.setProfileId(usuario.getId());
and xml markup:
<com.facebook.widget.ProfilePictureView
android:id="#+id/profilePicture"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="center_horizontal"
android:layout_marginBottom="10dp"
facebook:preset_size="normal"/>
Related
I use the following code do get an image from a regular image url:
try
{
url = new URL("http://example.com/test.jpg");
final Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
final ImageView imageView=(ImageView)findViewById(R.id.imageView2);
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
imageView.setImageBitmap(bmp);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
However, I want to download images that are displayed by html or php pages.
url = new URL("http://example.com/showimage.php");
If I use this, I get the following message:
SkImageDecoder::Factory returned null
How should I modify my code?
I recommend you to look at this library: http://jsoup.org/
This seems to be the solution when the page is redirected: http://blog.kosev.net/2011/01/follow-302-redirects-with.html
i am using facebook SDK 3.0 i have to get profile picture of user login.
Here is the code I use:
URL image_value = new URL("http://graph.facebook.com/"+id+"/picture" );
profPict=BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
But I don't get the desired result.
You should change your code following:
URL image_value = new URL("http://graph.facebook.com/"+id+"/picture" );
Possible GET parameters for the URL can be found here:
https://developers.facebook.com/docs/graph-api/reference/user/picture/
Use https:// instead of http:// i faced the same problem.
URL image_value = new URL("https://graph.facebook.com/"+id+"/picture" );
profPict = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
If you are trying to display profile pic in your app, use ProfilePictureView from Facebook SDK.
Refer This
Just call setProfileId(String profileId) on it.
It will take care of displaying the image.
String id = user.getId();
try {
URL url = new URL("http://graph.facebook.com/"+ id+ "/picture?type=large");
String image_path = uri.toString();
System.out.println("image::> " + image_path);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
Use ProfilePictureView from facebook sdk.
You can do something like this inside a thread:
String url = "http://graph.facebook.com/"+id+"/picture";
HttpConnection conn = new HttpConnection(url);
conn.openConnection();
Drawable d = Drawable.createFromStream(new BufferedInputStream(conn.getInputStream()), "image");
conn.close();
I hope it help you.
try this..
try {
imageURL = new URL("https://graph.facebook.com/" +
id+ "/picture?type=large");
Log.e("URL", imageURL.toString());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
try {
bitmap = BitmapFactory.decodeStream(imageURL
.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ProfileDp.setImageBitmap(bitmap);
Once your facebook account is logged into the application, simply do:
String url = Profile.getCurrentProfile().getProfilePictureUri(x, y).toString();
x and y are width and height.
See the doc : https://developers.facebook.com/docs/reference/android/current/class/Profile/
I am a learner and have been working on a home visitor app to get image from a URL of the visitor. Using the following code, which I found online, I was able to load image by adding an intent before the screen and adding a button on the screen saying "See Visitor Image" but now I want that my image should load as soon as the app launches. What changes could I make to do that? Thanks for your help.
OnClickListener getImageBtnOnClick = new OnClickListener() {
public void onClick(View view) {
Context context = view.getContext();
Editable ed = inputUrl.getText();
Drawable image = ImageOperations(context,ed.toString(),"image.jpg");
ImageView imgView = new ImageView(context);
imgView = (ImageView)findViewById(R.id.image1);
imgView.setImageDrawable(image);
}
};
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
inputUrl = ((EditText)findViewById(R.id.imageUrl));
inputUrl.setSingleLine();
inputUrl.setTextSize(11);
Button getImageButton = (Button)findViewById(R.id.getImageButton);
getImageButton.setOnClickListener(getImageBtnOnClick);
}
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view
Or on OnResume of ur activity start downloading the image form the url as u r doing now in the click listener of button in a separate thread to avoid blocking main UI thread. Once you completed the download you can update the image view using handler from the worker thread.
You can make use of async task also instead of creating your own thread and handler to update UI. for more infor about async task refer following link http://www.vogella.com/articles/AndroidPerformance/article.html
It is possible to post to a Facebook wall a message with image (not an image link, but image data)?
I did not find this possibility either in http://developers.facebook.com/docs/reference/api/post/ or in https://developers.facebook.com/docs/guides/attachments/.
And I was ready to put up with impossibility of doing it, but I came across documentation for SLComposeViewController class introduced in iOS 6.0 (http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html).
This class has a method - (BOOL)addImage:(UIImage *)image that does exactly what I need.
I program for Android and hence I cannot use it. But obviously this method must use facebook API. But I cannot find it: everything related to image posting requires url, not data.
So, is is possible in Android to post to a Facebook wall a message with image data?
EDIT: I posted the answer almost with your comment. You can use something like this to cast you Image from assets into a Bitmap.
InputStream bitmap = null;
try {
bitmap = getAssets().open("icon.png");
bmpImageGallery = BitmapFactory.decodeStream(bitmap);
} catch (IOException e) {
e.printStackTrace();
} finally {
bitmap.close();
}
This is how I display an Image from the Gallery via an Intent in the onActivityResult method:
targetURI = data.getData();
try {
bmpImageGallery = MediaStore.Images.Media.getBitmap(this.getContentResolver(), targetURI);
// SET THE IMAGE FROM THE GALLERY TO THE IMAGEVIEW
imgvwSelectedImage.setImageBitmap(bmpImageGallery);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is the code to upload the image:
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmpImageGallery.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle postImgGallery = new Bundle();
// ADD THE PHOTO DATA TO THE BUNDLE
postImgGallery.putByteArray("photo", data);
// ADD THE CAPTION FROM THE STRING finalStatusMessage TO THE BUNDLE
if (finalStatusMessage.equals("")) {
/***** DO NOTHING HERE *****/
} else {
postImgGallery.putString("caption", finalStatusMessage);
}
Utility.mAsyncRunner.request(userID + "/photos", postImgGallery, "POST", new PhotoUploadListener(), null);
NOTE: In this bit here "caption", finalStatusMessage, the caption can also be substituted with message. I have never seen any difference in the posts using either of these. But do check before using either, just to be safe. ;-)
This class is used to check the status of the upload:
private class PhotoUploadListener extends BaseRequestListener {
#Override
public void onComplete(String response, Object state) {
// DISPLAY A CONFIRMATION TOAST
}
}
Ok so I have setup a new Facebook app and I have the API and all that jazz setup also and have made successful posts to Facebook using the API. Here is my issue.
How do I format the text the way I want too??
For example:
description += "First line \r\n";
description += "Second line \r\n";
I am using the Facebook Android SDK and using the Feed Dialog approach as listed here
Also, I am using the feed dialog like so:
String description += "First line \r\n";
description += "Second line \r\n";
Facebook facebook = new Facebook("MY_APP_ID");
SetAccessToken(mContext, facebook);
params.putString("link", "");
params.putString("picture", "");
params.putString("name", "");
facebook.dialog(mContext, "feed", params, new Facebook.DialogListener() {
public void onFacebookError(FacebookError e) {
}
public void onError(DialogError e) {
}
public void onComplete(Bundle values) {
}
public void onCancel() {
}
});
Whenever, I do that it pulls up my Facebook dialog and the lines are not separated by line feeds. I also tried to use HTML such as
<p>Line 1</p>
<p>Line 2</p>
My guess is that I need to use another method in order to actually post formatted text, other than the feed dialog. I know that other Facebook apps are posting to users feeds with properly formatted text. Just not sure why the SDK doesn't offer the same functionality.
EDIT 1
Just to add this, the submission is actually in a URL format at the end anyway. I tried adding URL escape characters but that didn't seem to do anything for me.
String url = endpoint + "?" + Util.encodeUrl(parameters);
Then they pass that into a webview. So I am currently looking into this. Any advice is appreciated.
as far as I have researched...facebook doesn't allow it's domain image to be posted on wall through post. So, we can't use it. Now what I am doing is getting the imge through following code:
ImageView user_picture;
user_picture = (ImageView) findViewById(R.id.user_picture);
URL img_value = null;
Bitmap mIcon1 = null;
try {
img_value = new URL("http://graph.facebook.com/XXXX/picture");
try {
mIcon1 = BitmapFactory.decodeStream(img_value
.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mIcon1!=null){
user_picture.setImageBitmap(mIcon1);
}
if you want it to convert to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mIcon1.compress(Bitmap.CompressFormat.PNG, 100, baos);
b = baos.toByteArray();
Sending this image to my server and then posting to wall.
Have you tried:
String message = "<p>Line 1</p><p>Line 2</p>";
params.putString("message", Html.fromHtml(message).toString());