Show Avatar Facebook to ImageView
I used the code as follows to show up facebook avatar to ImageView
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView) findViewById(R.id.imgAvatar);
img.setImageBitmap(getBitmapFromURL("http://graph.facebook.com/"+"100002394015528"+"/picture"));
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStac开发者_JAVA技巧kTrace();
return null;
}
}`
But does it not work. Please help me.
http://graph.facebook.com/id/picture
doesn't return an image. It returns some response headers including a 302 redirect, and a location header.
Your example for instance redirects to: http://profile.ak.fbcdn.net/hprofile-ak-snc4/211619_100002394015528_568817_q.jpg
So instead of
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
You need to get the headers from the request, follow the location and then do what you were doing before. I don't know Android, or what language that is. (Java?) So I can't help with that, but I think this might be enough information to get you headed in the right direction.
Use this function for get real URL to avatar:
public static String getUrlFacebookUserAvatar(String name_or_idUser )
{
String address = "http://graph.facebook.com/"+name_or_idUser+"/picture";
URL url;
String newLocation = null;
try {
url = new URL(address);
HttpURLConnection.setFollowRedirects(false); //Do _not_ follow redirects!
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
newLocation = connection.getHeaderField("Location");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newLocation;
}
精彩评论