Android - 从URL添加到rootview的位图
我在从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中它告诉我它无法建立连接。我还在互联网的清单中设置了权限。我被可能是一个简单的修补程序的傻眼了。
您正试图在UI线程上运行网络操作(http连接)。你应该看看线程& asynctasks:http://developer.android.com/guide/components/processes-and-threads.html
感谢您指引我在正确的方向。另外,当我重新开始工作时,我一定会在明天发布logcat。 – bfen3774 2013-03-16 07:09:35
不要忘记当你的bug被修复时将主题标记为已解决 – Quanturium 2013-03-19 04:32:06
正在休假一周。我现在回到案例。线程和进程页面实际上是我的桌面背景atm。 – bfen3774 2013-03-25 17:02:00
@Quanturium的回答是一个开始。但是你真的应该发布你的logcat来查看你遇到的问题。 – DigCamara 2013-03-16 01:43:13