Android Universal Image Loader无法正常工作

时间:2015-12-04 05:15:18

标签: android

我想从网址加载照片并保存在我的Android应用程序的外部存储中,但在运行应用程序时出现 NetworkOnMainThreadException 问题。我正在尝试使用Universal Image Loader加载图像和存储到外部存储目录。谢谢。

这是我的代码

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_post);
        dbhelper = new MyDbHelper(this);
        dbhelper.onOpen(db);

 imageLoader = ImageLoader.getInstance();
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(CustomActionActivity.this));
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        Loaddata();
        new LosdImages().execute();

    }

 private class LosdImages extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            Loaddata();
            return null;
        }
    }
    public void Loaddata() {

        db = dbhelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from ActivityObjectList", null);

        if (cursor.moveToFirst())
        {
            do {
                imageName = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
                Log.e("imageName "," = "+imageName);
                String fileUrl = namespace + "/DownloadFile/FilePathMobile/ATTACHMENT/FileName/"+imageName;
                download_PngFileImgLoader(fileUrl, imageName);
                Log.e("imageName ", " DownLoaded Succecively !!! = " + imageName);
                pics.add(imageName);
            }
            while (cursor.moveToNext());
        }
        cursor.close();
    }

    void download_PngFileImgLoader(String fileUrl, String ImageName) {
        newFolder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "classnkk_images");
        File fileForImage = new File(newFolder, ImageName);

        try {
            InputStream sourceStream;
            File cachedImage = imageLoader.getInstance().getDiscCache().get(fileUrl);
            if (cachedImage != null && cachedImage.exists()) { // if image was cached by UIL
                sourceStream = new FileInputStream(cachedImage);
            } else { // otherwise - download image
                ImageDownloader downloader = new BaseImageDownloader(getApplicationContext());
                sourceStream = downloader.getStream(fileUrl, null);
            }
            if (sourceStream != null) {
                try {
                    OutputStream targetStream = new FileOutputStream(fileForImage);
                    try {
                        IoUtils.copyStream(sourceStream, targetStream, null);
                    } finally {
                        targetStream.close();
                    }
                } finally {
                    sourceStream.close();
                }
            }
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }


}

这是我的错误日志

 Process: com.example.tazeen.classnkk, PID: 3409
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tazeen.classnkk/com.example.tazeen.classnkk.CustomActionActivity}: android.os.NetworkOnMainThreadException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
            at android.app.ActivityThread.access$900(ActivityThread.java:147)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
            at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
            at libcore.io.IoBridge.connectErrno(IoBridge.java:154)
            at libcore.io.IoBridge.connect(IoBridge.java:122)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
            at java.net.Socket.connect(Socket.java:882)
            at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139)
            at com.android.okhttp.Connection.connect(Connection.java:148)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
            at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromNetwork(BaseImageDownloader.java:117)
            at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:88)
            at com.example.tazeen.classnkk.CustomActionActivity.download_PngFileImgLoader(CustomActionActivity.java:128)
            at com.example.tazeen.classnkk.CustomActionActivity.Loaddata(CustomActionActivity.java:108)
            at com.example.tazeen.classnkk.CustomActionActivity.onCreate(CustomActionActivity.java:84)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
            at android.app.ActivityThread.access$900(ActivityThread.java:147)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)

4 个答案:

答案 0 :(得分:2)

我的建议是使用Glide他们有缓存,错误处理等等

简单易用

File b = new File(Environment.getExternalStorageDirectory(), 
            "DCIM/Camera/IMG_20151028_192555.jpg");

Glide.with(MainActivity.this).load(c).
             error(R.drawable.empty_pic).
             placeholder(R.drawable.empty_pic).into(image2);

请参阅此link

答案 1 :(得分:2)

您必须在AsyncTask中编写网络操作,而不是在主Thread

删除此行格式 onCreate() ,您已在AsyncTask中调用。

    Loaddata();

答案 2 :(得分:1)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_post);
    dbhelper = new MyDbHelper(this);
    dbhelper.onOpen(db);

    imageLoader = ImageLoader.getInstance();
    ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(CustomActionActivity.this));
    options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    new LosdImages().execute();

   }

    private class LosdImages extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {
        Loaddata();
        return null;
    }

   public void Loaddata() {

    db = dbhelper.getWritableDatabase();
    Cursor cursor = db.rawQuery("select * from ActivityObjectList", null);

    if (cursor.moveToFirst())
    {
        do {
            imageName = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
            Log.e("imageName "," = "+imageName);
            String fileUrl = namespace + "/DownloadFile/FilePathMobile/ATTACHMENT/FileName/"+imageName;
            download_PngFileImgLoader(fileUrl, imageName);
            Log.e("imageName ", " DownLoaded Succecively !!! = " + imageName);
            pics.add(imageName);
        }
        while (cursor.moveToNext());
    }
    cursor.close();
}

 void download_PngFileImgLoader(String fileUrl, String ImageName) {
    newFolder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "classnkk_images");
    File fileForImage = new File(newFolder, ImageName);

    try {
        InputStream sourceStream;
        File cachedImage = imageLoader.getInstance().getDiscCache().get(fileUrl);
        if (cachedImage != null && cachedImage.exists()) { // if image was cached by UIL
            sourceStream = new FileInputStream(cachedImage);
        } else { // otherwise - download image
            ImageDownloader downloader = new BaseImageDownloader(getApplicationContext());
            sourceStream = downloader.getStream(fileUrl, null);
        }
        if (sourceStream != null) {
            try {
                OutputStream targetStream = new FileOutputStream(fileForImage);
                try {
                    IoUtils.copyStream(sourceStream, targetStream, null);
                } finally {
                    targetStream.close();
                }
            } finally {
                sourceStream.close();
            }
        }
    } catch (IOException ie) {
        ie.printStackTrace();
    }
}


}
}

我在代码中做了一些更改,导致NetworkMainThreadException。希望它能起作用

答案 3 :(得分:0)

您需要在班级中添加StrictMode.ThreadPolicy

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.all_post);     
   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   StrictMode.setThreadPolicy(policy);
.....
 }