Error of passing param paramenter from an Activity to a PageAdpter

2

Good evening,

I have an Activity Class that generates an Array String, I need to pass this array to another Class but this class is a PageAdapter.

What I need to do is take the FileArray variable from Activity and send it to PageAdapter.

imageView.setImageResource(Integer.parseInt(     )); // aqui eu preciso receber um array

But the way I've learned both classes has to be Activity.

Activity:

public class SwipeActivity extends Activity{

public static File[] files;
public static String pasta;

ViewPager viewPager;
CustomSwipeAdpter adpter;

File new_folder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.swipe_activity);


    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    Bundle bundle = getIntent().getExtras();

    if (bundle.containsKey("URLRevista") &&
            bundle.containsKey("NumPaginas") &&
            bundle.containsKey("Pasta")){

        String Url = bundle.getString("URLRevista");
        int NumPaginas = Integer.valueOf(bundle.getString("NumPaginas"));
        pasta = bundle.getString("Pasta");

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to data/data/yourapp/app_data/imageDir
        new_folder = cw.getDir(pasta, Context.MODE_PRIVATE);

        if (!new_folder.exists()){
            new_folder.mkdir();
        }

        // verifica a pasta se tem arquivo //
        files = new_folder.listFiles();

        if ((files.length > 0)) {
            String[] fileArray = new String[files.length];
            String[] filesResource = new String[files.length];
            for (int i = 0; i < files.length; ++i) {
                fileArray[i] = files[i].getAbsolutePath();

            }
           // depois de carregar o filearray eu preciso setar no Page Adapter //

        } else {

            ArrayList<String> stringArrayList = new ArrayList<String>();

            // Aqui insere as strings no array //
            for (int i = 1; i < NumPaginas; i++) {
                // Converter contador em string e add zero a esquerda //
                String formatCont = String.format("%02d", Integer.parseInt(String.valueOf(i)));
                // monta o Array com as Strings //

                String UrlMontada = (Url + pasta + "_" + formatCont + ".jpg");

                stringArrayList.add(UrlMontada);
            }
            new DownloadTask().execute(stringArrayList);
        }

    }
    viewPager = (ViewPager)findViewById(R.id.ViewPage);
    adpter = new CustomSwipeAdpter(this);
    viewPager.setAdapter(adpter);

}



class DownloadTask extends AsyncTask<ArrayList<String>, Integer, String> {
    ProgressDialog progressDialog;
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(SwipeActivity.this);
        progressDialog.setTitle("Download em progresso...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(ArrayList<String>... params) {

        ArrayList<String> path = params[0];

        for (String urlImage : path) {
            int file_length = 0;
            try {
                URL url = new URL(urlImage);
                URLConnection urlconnection = url.openConnection();
                urlconnection.connect(); // ok
                file_length = urlconnection.getContentLength();

                String fileName = Uri.parse(String.valueOf(url)).getLastPathSegment();

                File imput_file = new File(new_folder, fileName);

                InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
                byte[] data = new byte[1024];
                int total = 0;
                int count = 0;

                OutputStream outputStream = new FileOutputStream(imput_file);

                while ((count = inputStream.read(data)) != -1) {
                    total += count;
                    outputStream.write(data, 0, count);
                    int progress = (int) total * 100 / file_length;
                    publishProgress(progress);
                }
                inputStream.close();
                outputStream.close();

            } catch (MalformedURLException e) { e.printStackTrace();
            } catch (IOException e) { e.printStackTrace(); }
        }
        return "Download finalizado!";
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        progressDialog.hide();
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();

    }
}

Here is the PageAdapter class ...

public class CustomSwipeAdpter extends PagerAdapter {

private String[] image_resources;

private Context ctx;
private LayoutInflater layoutInflater;
private Resources resource;

public CustomSwipeAdpter(Context ctx) {
    this.ctx = ctx;
    resource = ctx.getResources();
}

@Override
public int getCount() {
    return image_resources.length;
}

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

@Override
public Object instantiateItem(ViewGroup container, int position){
    layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
    ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);



    imageView.setImageResource(Integer.parseInt(     )); // aqui eu preciso receber um array  

    imageView.setImageBitmap(
            decodeSampledBitmapFromResource(resource,
                    R.id.imageView, // aqui esta o problema
                    1080,
                    2560));

    container.addView(item_view);

    return item_view;
}

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

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}


public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 2;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}
    
asked by anonymous 10.05.2016 / 00:46

1 answer

1

Try using this onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.swipe_activity);


    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    Bundle bundle = getIntent().getExtras();

    String[] fileArray;

    if (bundle.containsKey("URLRevista") &&
        bundle.containsKey("NumPaginas") &&
        bundle.containsKey("Pasta")){

        String Url = bundle.getString("URLRevista");
        int NumPaginas = Integer.valueOf(bundle.getString("NumPaginas"));
        pasta = bundle.getString("Pasta");

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to data/data/yourapp/app_data/imageDir
        new_folder = cw.getDir(pasta, Context.MODE_PRIVATE);

        if (!new_folder.exists()){
            new_folder.mkdir();
        }

        // verifica a pasta se tem arquivo //
        files = new_folder.listFiles();

        if ((files.length > 0)) {
            fileArray = new String[files.length];
            String[] filesResource = new String[files.length];
            for (int i = 0; i < files.length; ++i) {
                fileArray[i] = files[i].getAbsolutePath();

            }
           // depois de carregar o filearray eu preciso setar no Page Adapter //

        } else {

            ArrayList<String> stringArrayList = new ArrayList<String>();

            // Aqui insere as strings no array //
            for (int i = 1; i < NumPaginas; i++) {
                // Converter contador em string e add zero a esquerda //
                String formatCont = String.format("%02d", Integer.parseInt(String.valueOf(i)));
                // monta o Array com as Strings //

                String UrlMontada = (Url + pasta + "_" + formatCont + ".jpg");

                stringArrayList.add(UrlMontada);
            }
            new DownloadTask().execute(stringArrayList);
        }

    }
    viewPager = (ViewPager)findViewById(R.id.ViewPage);
    adpter = new CustomSwipeAdpter(this, fileArray);
    viewPager.setAdapter(adpter);

}

As you can see, I passed the fileArray as a parameter in CustomSwipeAdpter. Now in the CustonSwipeAdapter compiler you get this array.

public CustomSwipeAdpter(Context ctx, String[] fileArray) {
    this.ctx = ctx;
    this.fileArray = fileArray;
    resource = ctx.getResources();
}

This way you can use fileArray in CustomSwipeAdpter. I hope I have helped.

    
10.05.2016 / 16:18