使用带位图的Pager-view的Image Slider不起作用

时间:2018-09-18 13:54:32

标签: android android-viewpager

亲爱的所有人,我使用PagerView制作滑块图像,并且一切顺利 如果我使用可绘制图像中的URL图像和String数组。

但是当我使用存储在APP目录中的文件无法正常工作时,您会在此处看到我的代码

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewPager"/>

</android.support.constraint.ConstraintLayout>

image_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>

BitmapPagerAdapter.java

package com.samcotec.pager2;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class BitmapPagerAdapter extends PagerAdapter {

    Context context;
    ArrayList<Bitmap> bitmaps;
    LayoutInflater layoutInflater;

    public BitmapPagerAdapter(Context context, ArrayList<Bitmap> bitmaps){
        this.context = context;
        this.bitmaps = bitmaps;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position){
        View itemView = layoutInflater.inflate(R.layout.image_layout, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
        imageView.setImageBitmap(bitmaps.get(position));
        container.addView(itemView);

        //listening to image click
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_LONG).show();
            }
        });

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }

}

MainActivity.java

package com.samcotec.pager2;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    ArrayList<Bitmap> bitmap = new ArrayList<Bitmap>();
    ViewPager viewPager;
    BitmapPagerAdapter bitmapPagerAdapter;
    String imgPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgPath = "/data/data/" + this.getPackageName() + "/" + "quranIMG/";

        File savefliepath = new File(imgPath);
        if(!savefliepath.exists()){
            System.out.println("file not exist: " + imgPath);
            savefliepath.mkdir();
        }else{
            //System.out.println("file exist: " + imgPath);
        }


        final AssetManager assetManager = getAssets();

        String[] list;
        InputStream f;
        String FileName;
        String URLPATH = "http://192.168.100.12/quran/";
        Integer StartFrom = 100;
        Integer EndTo = 150;

        for(int i = StartFrom; i <= EndTo; i++){
            FileName = "a-("+i+").png";
            File savefile = new File(imgPath + FileName);
            if(!savefile.exists()){
//                        tools.copyAssets(assetManager,Path);
                DownloadTask downloadTask = new DownloadTask(URLPATH,imgPath,FileName);

            }else{

            }
//            imgList.add(i);

        }

        // TODO : we must check internet connection if its ok
        for (int i = StartFrom; i<EndTo; i++){
            String b = imgPath + "a-("+i+").png";
           // System.out.println("file exists" + b);
            FileInputStream fiStream;
            File imgFile = new  File(getFilesDir(), b);

            Bitmap bit;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;

            if(imgFile.exists()){
                try{
                    fiStream    = MainActivity.this.openFileInput(b);
                    bit = BitmapFactory.decodeStream(fiStream);
                    bitmap.add(bit);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }else{
                DownloadTask downloadTask = new DownloadTask(URLPATH,imgPath,"a-("+i+").png");
                File imgFile1 = new  File(getFilesDir(), b);
                if(imgFile1.exists()) {
                    try{
                        fiStream    = MainActivity.this.openFileInput(b);
                        bit = BitmapFactory.decodeStream(fiStream);
                        bitmap.add(bit);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else{
                    bit = null;
                }
            }
        }

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        bitmapPagerAdapter = new BitmapPagerAdapter(MainActivity.this,bitmap);

        viewPager.setAdapter(bitmapPagerAdapter);
    }
}

我使用了一些工具来下载文件并将其存储在imgPath中 图像已下载并存储,没有问题 但是问题

bitmap.size();

始终为空,APP崩溃了

1 个答案:

答案 0 :(得分:0)

问题出在我的DownloadTask中,而不是代码本身。

我通过将下载任务更改为代码来解决它:

package com.samcotec.pager2;

import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownloadTask {

    public DownloadTask(final String url, final String savePath, final String saveName) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    System.out.println(url+saveName);
                    URL sourceUrl = new URL(url+saveName);
                    URLConnection conn = sourceUrl.openConnection();
                    conn.connect();
                    InputStream inputStream = conn.getInputStream();

                    int fileSize = conn.getContentLength();

                    File savefilepath = new File(savePath);
                    if (!savefilepath.exists()) {
                        savefilepath.mkdirs();
                    }
                    File savefile = new File(savePath+saveName);
                    if (savefile.exists()) {
                        savefile.delete();
                    }
                    savefile.createNewFile();

                    FileOutputStream outputStream = new FileOutputStream(savePath+saveName, true);

                    byte[] buffer = new byte[1024];
                    int readCount = 0;
                    int readNum = 0;
                    int prevPercent = 0;

                    while (readCount < fileSize && readNum != -1) {
                        readNum = inputStream.read(buffer);
                        if (readNum > -1) {
                            outputStream.write(buffer, 0, readNum);
                            readCount = readCount + readNum;

                            int percent = (int) (readCount * 100 / fileSize);
                            if (percent > prevPercent) {
                                System.out.println(percent);
                                //Toast.makeText(LoadPage.MY_CONTEXT,percent,Toast.LENGTH_LONG);
                                prevPercent = percent;
                            }
                        }
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    //Thread.sleep(50);


                } catch (Exception e) {
                    System.out.println( e);
                }
            }
        }).start();
    }



}