图像下载器崩溃

时间:2014-05-04 17:39:04

标签: android image bitmap

我尝试下载图片并将其设置为imageView,但我收到了以下logcat。

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();

        }

    }

}

这是我设置导致问题的图像的方式还是进度条?

1 个答案:

答案 0 :(得分:0)

主要问题是您正在尝试从MainThread下载图像,所有网络请求都应该在后台线程中执行。

因此OpenHttpConnection方法在尝试建立NetworkOnMainThreadException时收到了HttpURLConnection,并且它会返回IOException("Error connecting")

更改您的代码以使用AsyncTask下载图片。最好的方法是将ImageViewURL传递给下载方法并在后台执行

使用此优化代码下载图像并将其设置为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();
}

在设置内容视图后,从OnCreate调用此方法。

 img = (ImageView) findViewById(R.id.imageViewCategoryIcon);
    DownloadImage(img,
            "http://media-cache-ec0.pinimg.com/236x/af/38/5f/af385f471568e3e9f1d97bfe6e79652f.jpg");
相关问题