sara
sara

Reputation: 13

image view not showing the image with using thread

I'm using this code to show Images, as I run it without thread It works correctly but with using thread I just get Image views without any picture inside them. its important for me to use thread for this part of my program because its very slow :( here is my code :

        @Override
        public View getView(final int position,  View convertView, ViewGroup parent) {
            Log.e("sara" , "this part takes time");


            LayoutInflater inflater = getLayoutInflater();

            convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
            iv = (ImageView) convertView.findViewById(R.id.icon);
          final File file = new File(Uri.parse(getItem(position).toString()).getPath());
            //File file = new File("/text.jpg");

            Runnable runnable = new Runnable() {
                @Override
                public void run() {

                    Bitmap bmp = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            try {
                BitmapFactory.decodeStream(new FileInputStream(file), null, options);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            options.inJustDecodeBounds = false;
            options.inSampleSize = 2;
            try {
                bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        iv.setImageBitmap(bmp);

                }
            };
            new Thread(runnable).start();
            return convertView;
        }
    }

Upvotes: 0

Views: 84

Answers (1)

Bob
Bob

Reputation: 13850

Use AsyncTask.

Doc: https://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Do your heavy operation in doInBackground() and set the image to imageView in onPostExecute().

Upvotes: 1

Related Questions