Почему перестает работать приложение с 300 изображениями? - PullRequest
0 голосов
/ 27 октября 2018

Я создал приложение, которое состоит из 300 изображений.В начале приложения это работает snooth, никаких проблем.но когда я запускаю список, который загружает изображения, мое приложение перестает отвечать.Помогите мне.

Это мои MainActivity коды.Я копирую zip-файл изображения из папки активов во внутреннее хранилище и извлекаю изображения во внутреннее хранилище, а затем показываю их в виде сетки основной активности.

private void createDirs()
{
    File zipFileLoc = new File(storagePath, zipLoc);
    File unzipFileLoc = new File(storagePath, unzipLoc);
    File aksFileLoc = new File(storagePath, aks);
    if(zipFileLoc.exists() && unzipFileLoc.exists() && aksFileLoc.exists()){
        getFromStorage();
    }else{
        zipFileLoc.mkdirs();
        unzipFileLoc.mkdirs();
        aksFileLoc.mkdirs();

        copyAssets();
        unzip();

        getFromStorage();
    }
}

private void copyAssets()
{
    AssetManager assets = getAssets();
    String[] files = null;
    try{
        files = assets.list("");
    }catch(Exception e){
        Toast.makeText(this, "Failed to load images, please restart app", Toast.LENGTH_LONG).show();
    }
    for(String fileName : files){
        InputStream in = null;
        OutputStream out = null;
        try{
            in = assets.open(fileName);
            File zipOutFile = new File(storagePath + zipLoc, fileName);
            out =new FileOutputStream(zipOutFile);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        }catch(Exception e){
            Toast.makeText(this, "Failed to load images, please restart app", Toast.LENGTH_LONG).show();
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException
{
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

private void unzip()
{
    pd = new ProgressDialog(this);
    pd.setMessage("Please wait...");
    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pd.setCancelable(false);
    pd.show();

    new UnZipTask().execute(storagePath + zipLoc + "/AAGRIKOLISTATUS.zip", storagePath + aks);
}

private class UnZipTask extends AsyncTask<String, Void, Boolean>
{
    @SuppressWarnings("rawtypes")
    @Override
    protected Boolean doInBackground(String[] p1)
    {
        String filePath = p1[0];
        String destinationPath = p1[1];

        File archive = new File(filePath);
        try{
            ZipFile zf = new ZipFile(archive);
            for(Enumeration e = zf.entries(); e.hasMoreElements();){
                ZipEntry entry = (ZipEntry) e.nextElement();
                unzipEntry(zf, entry, destinationPath);
            }
            UnzipUtil d = new UnzipUtil(storagePath + zipLoc + "/AAGRIKOLISTATUS.zip", storagePath + aks);
            d.unzip();
        }catch(Exception e){
            return false;
        }

        return true;
    }

    @Override
    protected void onPostExecute(Boolean result)
    {
        pd.dismiss();
    }

    private void unzipEntry(ZipFile zf, ZipEntry entry, String destinationPath) throws IOException
    {
        if(entry.isDirectory()){
            createDir(new File(destinationPath, entry.getName()));
            return;
        }

        File outputFile = new File(destinationPath, entry.getName());
        if(!outputFile.getParentFile().exists()){
            createDir(outputFile.getParentFile());
        }

        BufferedInputStream inputs = new BufferedInputStream(zf.getInputStream(entry));
        BufferedOutputStream outputs = new BufferedOutputStream(new FileOutputStream(outputFile));

        try{

        }finally{
            outputs.flush();
            outputs.close();
            inputs.close();
        }
    }

    private void createDir(File file)
    {
        if(file.exists()){
            return;
        }

        if(!file.mkdirs()){
            throw new RuntimeException("Cannot create file " + file);
        }
    }
}

private void getFromStorage()
{
    File file = new File(storagePath, aks);
    if(file.isDirectory()){
        listfile= file.listFiles();
        for(int i = 0; i < listfile.length; i++){
            f.add(listfile[i].getAbsolutePath());
        }
    }

    ad = new ImageAdapter(this);
    gv.setAdapter(ad);
}
public class ImageAdapter extends BaseAdapter
{
    Context context;

    public ImageAdapter(Context cxt)
    {
        this.context = cxt;
    }

    @Override
    public int getCount()
    {
        return f.size();
    }

    @Override
    public Object getItem(int p1)
    {
        return p1;
    }

    @Override
    public long getItemId(int p1)
    {
        return p1;
    }

    @Override
    public View getView(int p1, View p2, ViewGroup p3)
    {
        ImageView iv = new ImageView(context);
        Bitmap bm = BitmapFactory.decodeFile(f.get(p1));
        iv.setImageBitmap(bm);
        iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        iv.setLayoutParams(new GridView.LayoutParams(240, 240));

        return iv;
    }
}

Вот мой main.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:gravity="center"
android:background="#00ff85">

<GridView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/aagrikolistatusphotoGridView"
    android:layout_above="@+id/aagrikolistatusphotocomgoogleandroidgmsadsAdView"
    android:columnWidth="90dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:horizontalSpacing="5dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="5dp"/>

1 Ответ

0 голосов
/ 27 октября 2018

Даже если вы распаковываете изображения в фоновом потоке, но загружаете их в основной поток, что вызывает сбой пользовательского интерфейса. Решение состоит в том, чтобы использовать Glide или Picasso для загрузки изображений в фоновом потоке. Пожалуйста, прочитайте Документацию Google: https://developer.android.com/topic/performance/graphics/load-bitmap#java
и попробуйте использовать один из них:
Скольжение: https://github.com/bumptech/glide
Пикассо: http://square.github.io/picasso/
Это должно помочь решить вашу проблему

...