Parameter crossing error from an Activity to a Pageadpter

Asked

Viewed 42 times

2

Good night,

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 Activity Filearray variable and send it to Pageadapter.

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

But the way I learned the two 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;
}
  • If you post the Pageadapter code we can help you. However, you tried to get past the Pageadapter maker?

  • Douglas I edited my doubt...I’m new on Android as I pass the build of Pageadpter. Valeu.

  • Thanks for your Edit, which object you really need to move to Customswipeadpter?

  • My project is an Online Magazine of the Type Veja, This is... How I am working out... I have a Manactivity with a List View and searches various web data with Json, all right. When I select one of the lines I call a Swipeactivity that downloads the pages of the Magazine for the App, I put the image paths in the Filearray, I want to take this Filearray and pass to the Custonswipeadapter and upload the images. In some youtube tutorials he straight arrow the Array with images in Drawable I need to exchange Drawable images for Filearray.

1 answer

1


Try to use 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 fileArray as parameter in Customswipeadpter. Now in the Custonswipeadapter constructor you take 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’ve helped.

  • thanks Douglas misses that even I needed.. thanks abs.

  • If the answer helped you please select it as sure, Briado

Browser other questions tagged

You are not signed in. Login or sign up in order to post.