2014-01-14 154 views
3
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中獲取Facebook個人資料圖片?

android.os.NetworkOnMainThreadException 

如何解決?

+0

你應該發佈一個新的問題,爲一個新的問題。 – James

+0

把它放在一個線程中。 –

回答

4

你的編輯(刪除)你的問題的一部分(僅供參考)

你錯過了第二/ 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); 
     } 
    } 


} 
0
Profile profile = Profile.getCurrentProfile(); 

Uri uri = profile.getProfilePictureUri(72, 72); //72 is the height and width of the profile pic, facebook will clip it for you. 

new Thread(new Runnable() { 
    @Override 
    public void run() { 
     try{ 
      URL newURL = new URL(uri.toString()); 
      Bitmap profilePic = BitmapFactory.decodeStream(newURL.openConnection().getInputStream());} 
     catch (IOException e) 
     {e.printStackTrace();} 
    } 
}).start(); 

這對我的作品。

相關問題