Getview() To Charge Images Inward Asynctask

Posted on

This post service show getView() loading images inwards AsyncTask, to brand UI responsive. Re-call my onetime “GridView example: charge images to GridView from SD Card inwards background“, it charge the files inwards backgroud, to brand the GridView start-up faster; exactly non inwards loading images inwards getView. Such that if the GridView going to charge large images, it volition block the UI inwards getView() together with brand the UI unresponsive.

The Android tutorial “Making ListView Scrolling Smooth” demo how to meliorate getView() past times loading images inwards AsyncTask.

The page suggest to check (v.position == position) to varify if this special hasn’t been recycled already. But it non run inwards this case. (actually, I don’t empathize how is the logic) In my implementation, roll-out images volition live on shown on wrong cell, exactly the in conclusion images volition supervene upon together with right it finally.

To charge images inwards AsyncTask volition non speed upwardly your ikon loading, exactly meliorate UI response.

package com.example.androidgridview;  import; import java.util.ArrayList; import java.util.Arrays;  import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import; import android.content.Context; import; import; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast;  world cast MainActivity extends Activity {    AsyncTaskLoadFiles myAsyncTaskLoadFiles;   world cast AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {      File targetDirector;   ImageAdapter myTaskAdapter;    world AsyncTaskLoadFiles(ImageAdapter adapter) {    myTaskAdapter = adapter;   }    @Override   protected void onPreExecute() {    String ExternalStorageDirectoryPath = Environment      .getExternalStorageDirectory().getAbsolutePath();     String targetPath = ExternalStorageDirectoryPath + "/test/";    targetDirector = novel File(targetPath);    myTaskAdapter.clear();        super.onPreExecute();   }    @Override   protected Void doInBackground(Void... params) {        File[] files = targetDirector.listFiles();    Arrays.sort(files);    for (File file : files) {     publishProgress(file.getAbsolutePath());     if (isCancelled()) break;    }    provide null;   }    @Override   protected void onProgressUpdate(String... values) {    myTaskAdapter.add(values[0]);    super.onProgressUpdate(values);   }    @Override   protected void onPostExecute(Void result) {    myTaskAdapter.notifyDataSetChanged();    super.onPostExecute(result);   }   }   world cast ImageAdapter extends BaseAdapter {    someone Context mContext;   ArrayList<String> itemList = novel ArrayList<String>();    world ImageAdapter(Context c) {    mContext = c;   }    void add(String path) {    itemList.add(path);   }      void clear() {    itemList.clear();   }      void remove(int index){    itemList.remove(index);   }    @Override   world int getCount() {    provide itemList.size();   }    @Override   world Object getItem(int position) {    // TODO Auto-generated method stub    provide itemList.get(position);   }    @Override   world long getItemId(int position) {    // TODO Auto-generated method stub    provide 0;   }    //getView charge bitmap ui thread   /*   @Override   world View getView(int position, View convertView, ViewGroup parent) {    ImageView imageView;    if (convertView == null) { // if it's non recycled, initialize unopen to           // attributes     imageView = novel ImageView(mContext);     imageView.setLayoutParams(new GridView.LayoutParams(220, 220));     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);     imageView.setPadding(8, 8, 8, 8);    } else {     imageView = (ImageView) convertView;    }     Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220,      220);     imageView.setImageBitmap(bm);    provide imageView;   }   */    //getView charge bitmap inwards AsyncTask   @Override   world View getView(final int position, View convertView, ViewGroup parent) {    ViewHolder holder;     ImageView imageView;    if (convertView == null) { // if it's non recycled, initialize unopen to           // attributes     imageView = novel ImageView(mContext);     imageView.setLayoutParams(new GridView.LayoutParams(220, 220));     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);     imageView.setPadding(8, 8, 8, 8);          convertView = imageView;          holder = novel ViewHolder();     holder.image = imageView;     holder.position = position;     convertView.setTag(holder);    } else {     //imageView = (ImageView) convertView;     holder = (ViewHolder) convertView.getTag();     ((ImageView)convertView).setImageBitmap(null);    }        //Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);    // Using an AsyncTask to charge the ho-hum images inwards a background thread    novel AsyncTask<ViewHolder, Void, Bitmap>() {        someone ViewHolder v;         @Override        protected Bitmap doInBackground(ViewHolder... params) {            v = params[0];            Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);            provide bm;        }         @Override        protected void onPostExecute(Bitmap result) {            super.onPostExecute(result);            //Not run for me!            /*            if (v.position == position) {                // If this special hasn't been recycled already,              // demo the ikon                v.image.setImageBitmap(result);            }            */             v.image.setImageBitmap(result);         }    }.execute(holder);     //imageView.setImageBitmap(bm);    //return imageView;    provide convertView;   }    world Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,     int reqHeight) {     Bitmap bm = null;    // First decode alongside inJustDecodeBounds=true to depository fiscal establishment check dimensions    in conclusion BitmapFactory.Options options = novel BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeFile(path, options);     // Calculate inSampleSize    options.inSampleSize = calculateInSampleSize(options, reqWidth,      reqHeight);     // Decode bitmap alongside inSampleSize laid    options.inJustDecodeBounds = false;    bm = BitmapFactory.decodeFile(path, options);     provide bm;   }    world int calculateInSampleSize(    BitmapFactory.Options options, int reqWidth, int reqHeight) {    // Raw tiptop together with width of ikon    in conclusion int tiptop = options.outHeight;    in conclusion int width = options.outWidth;    int inSampleSize = 1;     if (height > reqHeight || width > reqWidth) {     if (width > height) {      inSampleSize = Math.round((float) tiptop        / (float) reqHeight);     } else {      inSampleSize = Math.round((float) width / (float) reqWidth);     }    }     provide inSampleSize;   }      cast ViewHolder {             ImageView image;             int position;         }   }   ImageAdapter myImageAdapter;   @Override  world void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);    in conclusion GridView gridview = (GridView) findViewById(;   myImageAdapter = novel ImageAdapter(this);   gridview.setAdapter(myImageAdapter);    /*    * Move to asyncTaskLoadFiles String ExternalStorageDirectoryPath =    * Environment .getExternalStorageDirectory() .getAbsolutePath();    *     * String targetPath = ExternalStorageDirectoryPath + "/test/";    *     * Toast.makeText(getApplicationContext(), targetPath,    * Toast.LENGTH_LONG).show(); File targetDirector = novel    * File(targetPath);    *     * File[] files = targetDirector.listFiles(); for (File file : files){    * myImageAdapter.add(file.getAbsolutePath()); }    */   myAsyncTaskLoadFiles = novel AsyncTaskLoadFiles(myImageAdapter);   myAsyncTaskLoadFiles.execute();    gridview.setOnItemClickListener(myOnItemClickListener);      Button buttonReload = (Button)findViewById(;   buttonReload.setOnClickListener(new OnClickListener(){     @Override    world void onClick(View arg0) {          //Cancel the previous running task, if exist.     myAsyncTaskLoadFiles.cancel(true);          //new unopen to other ImageAdapter, to forbid the adapter convey     //mixed files     myImageAdapter = novel ImageAdapter(MainActivity.this);     gridview.setAdapter(myImageAdapter);     myAsyncTaskLoadFiles = novel AsyncTaskLoadFiles(myImageAdapter);     myAsyncTaskLoadFiles.execute();    }});   }   OnItemClickListener myOnItemClickListener = novel OnItemClickListener() {    @Override   world void onItemClick(AdapterView<?> parent, View view, int position,     long id) {    String prompt = "remove " + (String) parent.getItemAtPosition(position);    Toast.makeText(getApplicationContext(), prompt, Toast.LENGTH_SHORT)      .show();        myImageAdapter.remove(position);    myImageAdapter.notifyDataSetChanged();    }  };  } 


<LinearLayout xmlns:android=""     xmlns:tools=""     android:layout_width="match_parent"     android:layout_height="match_parent"      android:orientation="vertical">      <Button         android:id="@+id/reload"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Reload"/>     <GridView         android:id="@+id/gridview"         android:layout_width="fill_parent"          android:layout_height="fill_parent"         android:columnWidth="220dp"         android:numColumns="auto_fit"         android:verticalSpacing="10dp"         android:horizontalSpacing="10dp"         android:stretchMode="columnWidth"         android:gravity="center"/>  </LinearLayout> 

Permission of “android.permission.READ_EXTERNAL_STORAGE” is needed to read storage.

 charge images to GridView from SD Card inwards background getView() to charge images inwards AsyncTaskDownload the files.

– Improve JPG loading alongside ExifInterface.getThumbnail()