2013-03-16 59 views
0

我在從URL中拉取位圖時遇到了一些問題。我在Stack上使用了另一個問題的例子,但它不會加載圖像。下面是代碼:Android - 從URL添加到rootview的位圖

public class Image extends Activity{ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Bitmap bitmap = DownloadImage("http://cogadget.com/cogadget/wp-content/uploads/2010/05/Android-Logo-50x50.jpg"); 
    ImageView img = (ImageView) findViewById(R.id.imageView1); 
    img.setImageBitmap(bitmap); 
} 

private InputStream OpenHttpConnection(String urlString) throws IOException { 
    InputStream in = null; 
    int response = -1; 

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection(); 

    if (!(conn instanceof HttpURLConnection)) 
     throw new IOException("Not an HTTP connection"); 


    try { 
     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 
     response = httpConn.getResponseCode(); 
     if (response == HttpURLConnection.HTTP_OK) { 
      in = httpConn.getInputStream(); 
     } 
    } catch (Exception ex) { 
     throw new IOException("Error connecting"); 

    } 
    return in; 
} 

private Bitmap DownloadImage(String URL) { 
    Bitmap bitmap = null; 
    InputStream in = null; 

    try { 
     in = OpenHttpConnection(URL); 
     bitmap = BitmapFactory.decodeStream(in); 
     in.close(); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    return bitmap; 
} 

}

我試圖來用URL位圖的ImageView的。我可以在我的模擬器上連接到互聯網,但在logcat中它告訴我它無法建立連接。我還在互聯網的清單中設置了權限。我被可能是一個簡單的修補程序的傻眼了。

+0

@Quanturium的回答是一個開始。但是你真的應該發佈你的logcat來查看你遇到的問題。 – DigCamara 2013-03-16 01:43:13

回答

0

您正試圖在UI線程上運行網絡操作(http連接)。你應該看看線程& asynctasks:http://developer.android.com/guide/components/processes-and-threads.html

+0

感謝您指引我在正確的方向。另外,當我重新開始工作時,我一定會在明天發佈logcat。 – bfen3774 2013-03-16 07:09:35

+0

不要忘記當你的bug被修復時將主題標記爲已解決 – Quanturium 2013-03-19 04:32:06

+0

正在休假一週。我現在回到案例。線程和進程頁面實際上是我的桌面背景atm。 – bfen3774 2013-03-25 17:02:00