Android 图像下载程序崩溃
我正在尝试下载一个图像并将其设置为imageView,但我得到以下日志Android 图像下载程序崩溃,android,image,bitmap,Android,Image,Bitmap,我正在尝试下载一个图像并将其设置为imageView,但我得到以下日志 05-04 23:04:52.565: W/ActivityThread(4353): Application com.itcuties.app is waiting for the debugger on port 8100... 05-04 23:04:52.575: I/System.out(4353): Sending WAIT chunk 05-04 23:04:52.815: I/dalvikvm(4353):
05-04 23:04:52.565: W/ActivityThread(4353): Application com.itcuties.app is waiting for the debugger on port 8100...
05-04 23:04:52.575: I/System.out(4353): Sending WAIT chunk
05-04 23:04:52.815: I/dalvikvm(4353): Debugger is active
05-04 23:04:52.975: I/System.out(4353): Debugger has connected
05-04 23:04:52.975: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:53.175: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:53.375: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:53.575: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:53.775: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:53.975: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:54.175: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:54.375: I/System.out(4353): waiting for debugger to settle...
05-04 23:04:54.575: I/System.out(4353): debugger has settled (1499)
05-04 23:04:54.835: D/ProgressBar(4353): setProgressDrawable mProgressDrawable = null, d = android.graphics.drawable.LayerDrawable@42344d10needUpdate = false
05-04 23:04:54.835: D/ProgressBar(4353): setProgressDrawable drawableHeight = 32
05-04 23:04:54.835: D/ProgressBar(4353): setProgress = 0
05-04 23:04:54.835: D/ProgressBar(4353): setProgress = 0, fromUser = false
05-04 23:04:54.835: D/ProgressBar(4353): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 100
05-04 23:04:54.865: W/System.err(4353): java.io.IOException: Error connecting
05-04 23:04:54.875: W/System.err(4353): at com.itcuties.app.SplashActivity.OpenHttpConnection(SplashActivity.java:79)
05-04 23:04:54.875: W/System.err(4353): at com.itcuties.app.SplashActivity.DownloadImage(SplashActivity.java:41)
05-04 23:04:54.875: W/System.err(4353): at com.itcuties.app.SplashActivity.onCreate(SplashActivity.java:95)
05-04 23:04:54.875: W/System.err(4353): at android.app.Activity.performCreate(Activity.java:5372)
05-04 23:04:54.875: W/System.err(4353): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
05-04 23:04:54.875: W/System.err(4353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
05-04 23:04:54.875: W/System.err(4353): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
05-04 23:04:54.875: W/System.err(4353): at android.app.ActivityThread.access$700(ActivityThread.java:168)
05-04 23:04:54.885: W/System.err(4353): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
05-04 23:04:54.885: W/System.err(4353): at android.os.Handler.dispatchMessage(Handler.java:99)
05-04 23:04:54.885: W/System.err(4353): at android.os.Looper.loop(Looper.java:176)
05-04 23:04:54.885: W/System.err(4353): at android.app.ActivityThread.main(ActivityThread.java:5493)
05-04 23:04:54.885: W/System.err(4353): at java.lang.reflect.Method.invokeNative(Native Method)
05-04 23:04:54.885: W/System.err(4353): at java.lang.reflect.Method.invoke(Method.java:525)
05-04 23:04:54.885: W/System.err(4353): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
05-04 23:04:54.885: W/System.err(4353): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
05-04 23:04:54.885: W/System.err(4353): at dalvik.system.NativeStart.main(Native Method)
这是我的活动
package com.itcuties.app;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.itcuties.app.reader.data.RssAtomItem;
import com.itcuties.app.reader.data.RssResults;
import com.itcuties.app.util.atom.RssAtomReader;
/**
* Application splash screen. It also loads data.
*
* @author ITCuties
*
*/
public class SplashActivity extends Activity {
private ProgressBar progressBar;
public ImageView img;
public Toast t;
public 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;
}
@SuppressWarnings("unused")
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;
}
public String done = "Done";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Bitmap bitmap =
DownloadImage(
"http://media-cache-ec0.pinimg.com/236x/af/38/5f/af385f471568e3e9f1d97bfe6e79652f.jpg");
img = (ImageView) findViewById(R.id.imageViewCategoryIcon);
img.setImageBitmap(bitmap);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
progressBar.setProgress(0); // No progress so far
// Download data in the new thread
GetRSSDataTask grdt = new GetRSSDataTask();
grdt.execute("http://blanketcoffee.blogspot.com/feeds/posts/default");
}
/**
* Read RSS channel data.
*
* @author ITCuties
*
*/
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssAtomItem> > {
@Override
protected List<RssAtomItem> doInBackground(String... urls) {
try {
// Create RSS reader
RssAtomReader rssReader = new RssAtomReader(urls[0]);
rssReader.setProgressBar(progressBar); // Set the progress bar to show real progress
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("BlanketCoffeeRSS", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(List<RssAtomItem> results) {
// When the download is done the main activity needs to be started
Intent i = new Intent(SplashActivity.this, ListPostsActivity.class);
// You might find this not right to use a static attribute to pass data between the
// the activities in the application. We tried to pass the List of the RssAtomItem
// object with no luck although RssAtomItem implemented Serializable interface.
// ListPostActivity read null values. So this is the engineer's solution. It works :)
RssResults.setResults(results); //We need to set the results of the download process
// Show 100% progress
progressBar.setProgress(100);
Toast.makeText(getApplicationContext(), R.string.done, t.LENGTH_SHORT).show();
// Start new activity and finish this splash activity
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
}
}
package com.itcuties.app;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.URLConnection;
导入java.util.List;
导入android.app.Activity;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.ImageView;
导入android.widget.ProgressBar;
导入android.widget.Toast;
导入com.itcuties.app.reader.data.RssAtomItem;
导入com.itcuties.app.reader.data.RssResults;
导入com.itcuties.app.util.atom.RssAtomReader;
/**
*应用程序启动屏幕。它还加载数据。
*
*@author-ITCuties
*
*/
公共课堂活动扩展了活动{
私人ProgressBar ProgressBar;
公共图像视图img;
公众敬酒;
公共位图下载图像(字符串URL)
{
位图=空;
InputStream in=null;
试一试{
in=OpenHttpConnection(URL);
位图=BitmapFactory.decodeStream(in);
in.close();
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
返回位图;
}
@抑制警告(“未使用”)
私有InputStream OpenHttpConnection(字符串urlString)
抛出IOException
{
InputStream in=null;
int响应=-1;
URL=新URL(URL字符串);
URLConnection conn=url.openConnection();
if(!(HttpURLConnection的连接实例))
抛出新IOException(“非HTTP连接”);
试一试{
HttpURLConnection httpConn=(HttpURLConnection)conn;
httpConn.setAllowUserInteraction(假);
httpConn.setInstanceFollowRedirects(真);
httpConn.setRequestMethod(“GET”);
httpConn.connect();
response=httpConn.getResponseCode();
if(response==HttpURLConnection.HTTP\u OK){
in=httpConn.getInputStream();
}
}
捕获(例外情况除外)
{
抛出新IOException(“连接错误”);
}
返回;
}
公共字符串done=“done”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
位图=
下载图像(
"http://media-cache-ec0.pinimg.com/236x/af/38/5f/af385f471568e3e9f1d97bfe6e79652f.jpg");
img=(ImageView)findViewById(R.id.imageViewCategoryIcon);
设置图像位图(位图);
progressBar=(progressBar)findViewById(R.id.progressBar);
progressBar.setProgress(0);//到目前为止没有进展
//在新线程中下载数据
GetRSSDataTask grdt=新的GetRSSDataTask();
grdt.execute(“http://blanketcoffee.blogspot.com/feeds/posts/default");
}
/**
*读取RSS频道数据。
*
*@author-ITCuties
*
*/
私有类GetRSSDataTask扩展异步任务{
@凌驾
受保护列表doInBackground(字符串…URL){
试一试{
//创建RSS阅读器
RssAtomReader rssReader=新的RssAtomReader(URL[0]);
rssReader.setProgressBar(progressBar);//设置进度条以显示实际进度
//解析RSS,获取项目
返回rssReader.getItems();
}捕获(例外e){
Log.e(“blanktcoffers”,e.getMessage());
}
返回null;
}
@凌驾
受保护的void onPostExecute(列出结果){
//下载完成后,需要启动主要活动
意图i=新意图(SplashActivity.this、ListPostsActivity.class);
//您可能会发现使用静态属性在
//应用程序中的活动。我们试图传递RssAtomItem列表
//对象,但RssAtomItem实现了可序列化接口。
//ListPostActivity读取空值。所以这是工程师的解决方案。它的工作原理:)
setResults.setResults(results);//我们需要设置下载过程的结果
//显示100%的进度
progressBar.setProgress(100);
Toast.makeText(getApplicationContext(),R.string.done,t.LENGTH_SHORT).show();
//启动新活动并完成此启动活动
SplashActivity.this.Start触觉(i);
SplashActivity.this.finish();
}
}
}
是我设置图像的方式导致了问题还是进度条导致了问题?主要问题是您试图从
主线程下载图像,所有网络请求都应该在后台线程中执行
因此,OpenHttpConnection
方法在尝试建立HttpURLConnection
时收到一个NetworkOnMainThreadException
,并抛出IOException(“错误连接”)
使用AsyncTask
更改代码以下载图像。最好的方法是将ImageView
和URL
传递给下载方法并在后台执行
使用此优化代码下载图像并将其设置为ImageView
public void DownloadImage(final ImageView imageView , final String url)
{
new AsyncTask<Void, Integer, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
InputStream inputStream = new URL(url).openConnection().getInputStream();
return BitmapFactory.decodeStream(inputStream);
} catch (Exception ex) {
// handle the exception here
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}.execute();
}
img = (ImageView) findViewById(R.id.imageViewCategoryIcon);
DownloadImage(img,
"http://media-cache-ec0.pinimg.com/236x/af/38/5f/af385f471568e3e9f1d97bfe6e79652f.jpg");