简体   繁体   English

Android Universal Image Loader无法正常工作

[英]Android Universal Image Loader not working

I want to load photo from url and save in external storage in my Android Application but I got NetworkOnMainThreadException issue while run the application .I'm trying to use Universal Image Loader for loading images and storing to external storage directory.Thanks . 我想从url加载照片并保存在我的Android应用程序的外部存储中,但是在运行应用程序时遇到NetworkOnMainThreadException问题。我试图使用Universal Image Loader加载图像并将其存储到外部存储目录中。

Here is my code 这是我的代码

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


}

Here is my Error log 这是我的错误日志

 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)

My Suggestion to you is use Glide they have caching ,error handling and lots more 我对您的建议是使用Glide它们具有缓存,错误处理等功能

Simple to use 使用简单

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

See this link 看到这个链接

You have to write network operation in AsyncTask not in Main Thread 您必须在AsyncTask而不是在主Thread编写网络操作

Remove this line form onCreate() method, you have already called in AsyncTask . 删除此行窗体onCreate()方法,您已经在AsyncTask调用了它。

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


}
}

I made some changes in your code which is causing of NetworkMainThreadException. 我对您的代码进行了一些更改,这些更改导致NetworkMainThreadException。 Hope it will work 希望它能工作

You need to add StrictMode.ThreadPolicy in your class. 您需要在类中添加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);
.....
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM