如何在Android中获取Facebook个人资料图片?

时间:2014-01-14 02:09:12

标签: android facebook facebook-graph-api sdk

img_url = new URL("http://graph.facebook.com/" + user.getId() + "/picture?type=large");
                            InputStream is = img_url.openConnection().getInputStream();
                            Bitmap avatar;
                            avatar = BitmapFactory.decodeStream(is);
                            ivAvatar.setImageBitmap(avatar);

当我获取Facebook个人资料照片时,发生以下错误。

android.os.NetworkOnMainThreadException

如何解决?

1 个答案:

答案 0 :(得分:5)

您编辑(删除)的部分问题(仅供参考)

你错过了http:// http://graph.facebook.com/100001119045663/picture?type=large中的第二个/。

 java.net.UnknownHostException: http:/graph.facebook.com/100001119045663/picture?type=large

java.net.UnkownHostException描述它无法访问URL,无论是连接问题还是格式错误/无效的URL。

第二部分 - 问题添加  NetworkOnMainThread非常具有描述性。如果您正在从onCreate,onResume等调用函数,那么您正在UI线程上执行代码。这意味着如果你正在处理代码,你可以冻结UI。您需要创建一个单独的任务或线程。有关我所说的内容以及如何实施解决方案的更多信息,请参阅http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

TLDR版本......

package de.vogella.android.asynctask;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import de.vogella.android.asyntask.R;

 import android.app.Activity;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.TextView;

public class ReadWebpageAsyncTask extends Activity {
      private TextView textView;

   @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    HTTPExample task = new HTTPExample ();
    task.execute(new String[] { "http://pictureurl.com/image.jpg" });
  }

  private class HTTPExample extends AsyncTask<String, Void, String> {
         @Override
        protected String doInBackground(String... urls) {
        //urls is an array not a string, so iterate through urls.
        //Get Picture Here - BUT DONT UPDATE UI, Return a reference of the object
        return response;
        }

         @Override
         protected void onPostExecute(String result) {
         //Update UI
         Log.i("Result", result);
       }
   }


}