How to generate thumbnails of a bitmap using Asynctask?

Asked

Viewed 263 times

0

I have a Fragmentactivity that has a listview, in each item there is a button to open a Dialog, in this Dialog another listview is run with an Adapter that has a Textview and an Imageview, the list comes from a photo directory, wanted to put these photos as thumbnails, those thumbnails, I managed to do this without using the Asynctask, however, it got a little heavy as I have to compress the bitmaps, according to my studies, the best way is to use an Asynctask to perform the heavy process, I did it and it performs, however, the bitmap does not appear in the respective Imageview. I’ll put the code in order.

Dialogfragmentlistfotos.class

public class DialogFragmentListFotos extends DialogFragment {

private ListView listView;
private String path, title;


public static DialogFragmentListFotos newInstance(Bundle bundle) {
    DialogFragmentListFotos f = new DialogFragmentListFotos();
    f.setArguments(bundle);
    return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(STYLE_NORMAL, android.R.style.Theme_DeviceDefault_Light_Dialog);
    path = getArguments().getString("path");
    title = getArguments().getString("title");
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    String fotosDaOcupacao = getActivity().getString(R.string.fotosDaOcupacao);
    dialog.setTitle(fotosDaOcupacao + " " + title);
    return dialog;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.dialog_list_fotos, null);

    ListView listView = (ListView) view.findViewById(R.id.listView_fotos);
    Button cancelar = (Button) view.findViewById(R.id.button_cancel_list_fotos);

    final File file = new File(path);
    final File[] files = file.listFiles();
    ArrayList<String> stringArrayList = new ArrayList<String>();
    ArrayList<File> fileArrayList = new ArrayList<File>();
    for (int i = 0; i < files.length; i++) {
        stringArrayList.add(files[i].getName());
        fileArrayList.add(files[i]);
    }
    //ArrayAdapter<String> filesArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_selectable_list_item, theNamesOfFiles);
    ArrayAdapter<File> filesArrayAdapter = new ArrayAdapterFotos(getActivity(), R.layout.adapter_d_list_fotos, fileArrayList);

    cancelar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getDialog().dismiss();
        }
    });

    listView.setAdapter(filesArrayAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            File file = new File(path + "/" + files[position].getName());
            String type = getType(file);
            Intent it = new Intent();
            it.setAction(android.content.Intent.ACTION_VIEW);
            it.setDataAndType(Uri.fromFile(file), type);

            try {
                getActivity().startActivity(it);
            } catch (Exception e) {
                String appNessNaoEncontrado = getActivity().getString(R.string.appNessNaoEncontrado);
                ToastManager.show(getActivity(), appNessNaoEncontrado, ToastManager.ERROR, ToastManager.LENGTH_LONG);
            }
        }
    });

    return view;
}

private String getType(File file) {
    String type = null;
    try {
        URL u = file.toURL();
        URLConnection uc = null;
        uc = u.openConnection();
        type = uc.getContentType();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return type;
}
}

Arrayadapterfotos.class

public class ArrayAdapterFotos extends ArrayAdapter<File> {

private final int resourceId;
private ArrayList<File> files;
private Context context;
private int pos;
public ImageView imageView;

public ArrayAdapterFotos(Context context, int resource, ArrayList<File> files) {
    super(context, resource, files);
    this.resourceId = resource;
    this.files = files;
    this.context = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Log.i("Posição", String.valueOf(position));
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
    }
    pos = position;
    imageView = (ImageView) convertView.findViewById(R.id.imageView_foto_thumbail);
    TextView textView = (TextView) convertView.findViewById(R.id.textView_nome_foto);
    textView.setText(files.get(position).getName());

    BitmapTask bitmapTask = new BitmapTask();
    bitmapTask.execute(files.get(position).getAbsolutePath());

    return convertView;
}

public class BitmapTask extends AsyncTask<String, Bitmap, Bitmap> {

    private String data;

    @Override
    protected Bitmap doInBackground(String... params) {
        int h = 48; // height in pixels
        int w = 48; // width in pixels
        data = params[0];
        Bitmap bitmap =       ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(data), h, w);
        publishProgress(bitmap);
        return bitmap;
    }

    @Override
    protected void onProgressUpdate(Bitmap... values) {
        imageView.setImageBitmap(values[0]);
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }
 }
}
  • Did you ever think of a lib for the Humbs? https://github.com/gabrielemariotti/cardslib/blob/master/doc/THUMBNAIL.md https://github.com/Bearded-Hen/Android-Bootstrap

1 answer

1

Try this.

Remove the public statement ImageView imageView; Adapter

Add the code to:

//adicione esse atributo no seu adapter
private LayoutInflater mInflater;

//adicione dentro do constutor este trecho de código
public ArrayAdapterFotos(Context context, int resource, ArrayList<File> files) {
    //...
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return files.size();
}
public File getItem(int position) {
    return files.get(position);
}
public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ItemSuporte itemHolder;
     if (convertView == null) {
          convertView = mInflater.inflate(resourceId, null);
          itemHolder = new ItemSuporte();
          itemHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView_foto_thumbail);
          itemHolder.textView = (TextView) convertView.findViewById(R.id.textView_nome_foto);
          convertView.setTag(itemHolder);
     }else{
          //se a view já existe pega os itens.
        itemHolder = (ItemSuporte) convertView.getTag();
     }
    itemHolder.textView.setText(files.get(position).getName());

    BitmapTask bitmapTask = new BitmapTask(itemHolder.imageView);
    bitmapTask.execute(files.get(position).getAbsolutePath());
   //...
}
private class BitmapTask extends AsyncTask<String, Bitmap, Bitmap> {
    private ImageView imageView
    private String data;

    public BitmapTask(ImageView imageView){
        this.imageView = imageView;
    }
    //...
}

private class ItemSuporte {

    public ImageView imageView;
    public TextView textView;

}
  • Now come the pictures! But something weird happened, he uploads the images in the first listview item, showing all the images as if they were frame by frame, after that he uploads the images throughout the listview, I already removed the onProgressUpdate from Asynctask and still continues with it.

  • You need to create a support class, you are declaring Imageview within Adapter, so imageView is global, Voce has to have an Imageview for each item in the list. I’ll adjust the answer.

  • for you to understand and work do this inside getView: ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView_foto_thumbail);

  • After your resolution I did this, I removed the global statement from Imageview and put exactly as you did, but the problem there is the same.

  • Imageview thumbImage = (Imageview) convertView.findViewById(R.id.imageView_foto_thumbail);

  • I am working here possibly may have error in the code as I am finding I vvo adjusting. See if this way works.

  • Okay, I’m grateful for your help and your willingness, but you still have the same problem, even with this solution.

Show 2 more comments

Browser other questions tagged

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