From 105b7de4c92deb9c338d8c457188f187c82c7014 Mon Sep 17 00:00:00 2001 From: leninbooter Date: Sat, 9 Aug 2014 13:24:35 -0430 Subject: [PATCH] Gridview fast + disk and memory cache just missing some cleaning of comments and loading bar --- .../com/whatsup/whatsup/ImageAdapter.java | 121 ++++++++ .../whatsup/ImageDownloaderAsyncTask.java | 157 +++++++++++ .../java/com/whatsup/whatsup/ImageLoader.java | 23 +- .../whatsup/WhatWasHereFragmentGV.java | 260 +++--------------- 4 files changed, 321 insertions(+), 240 deletions(-) create mode 100644 whatsup/src/main/java/com/whatsup/whatsup/ImageAdapter.java create mode 100644 whatsup/src/main/java/com/whatsup/whatsup/ImageDownloaderAsyncTask.java diff --git a/whatsup/src/main/java/com/whatsup/whatsup/ImageAdapter.java b/whatsup/src/main/java/com/whatsup/whatsup/ImageAdapter.java new file mode 100644 index 0000000..2db3f65 --- /dev/null +++ b/whatsup/src/main/java/com/whatsup/whatsup/ImageAdapter.java @@ -0,0 +1,121 @@ +package com.whatsup.whatsup; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Point; +import android.os.Handler; +import android.util.Log; +import android.view.Display; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.GridView; +import android.widget.ImageView; +import android.widget.ViewSwitcher; + +import java.util.HashMap; + +/** + * Created by alenin on 09/08/2014. + */ +public class ImageAdapter extends BaseAdapter { + private Context mContext; + private LayoutInflater mInflater; + private int mResourceId; + private int mQuantity; + private int hw; + private HashMap mImages = new HashMap(); + + private static final int PROGRESSBARINDEX = 0; + private static final int IMAGEVIEWINDEX = 1; + + private Handler mHandler; + private ImageLoader mImageLoader = null; + + public ImageAdapter(Context mContext, int resourceId, int quantity) { + this.mContext = mContext; + this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + this.mQuantity = quantity; + this.mResourceId = resourceId; + for( int i=0; i { + Activity activity; + + private onImageDownloaderAsyncTaskListener mListener; + + public interface onImageDownloaderAsyncTaskListener { + public void PickDownloadedImage(String path); + } + + public ImageDownloaderAsyncTask(Activity activity, WhatWasHereFragmentGV whatWasHereFragmentGV, Executor executor, String... urls) { + this.activity = activity; + mListener = whatWasHereFragmentGV; + //execute(urls); + executeOnExecutor( executor, urls); + } + + protected String doInBackground(String... urls) { + InputStream iStream = null; + String imgUrl = Params.CDN + urls[0]; + Log.d("ImageLoaderTask will download: ", imgUrl); + URL url; + File tmpFile = null; + try { + File cacheDirectory = activity.getCacheDir(); + tmpFile = new File( cacheDirectory.getPath() + "/" + urls[1] ); + if( true ) { + Log.d("Image was on cache", "no"); + url = new URL(imgUrl); + Bitmap b; + int hw; + Display display = activity.getWindowManager().getDefaultDisplay(); + Point size = new Point(); + display.getSize(size); + + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); + urlConnection.connect(); + iStream = urlConnection.getInputStream(); + FileOutputStream fOutStream = new FileOutputStream(tmpFile); + hw = size.x / 3; + b = BitmapFactory.decodeStream(iStream); + b = Bitmap.createScaledBitmap(b, hw, hw, false); + b.compress(Bitmap.CompressFormat.JPEG, 90, fOutStream); + fOutStream.flush(); + fOutStream.close(); + }else { + Log.d("Image was on cache", "yes"); + } + } catch (Exception e) { + Log.d("Exception on Imagedownloader task", e.getMessage()); + e.printStackTrace(); + } catch ( OutOfMemoryError ome ) { + return null; + } + return tmpFile.getPath(); + } + + protected void onPostExecute(String result) { + if( result != null ) + mListener.PickDownloadedImage( result ); + else { + Toast.makeText(activity, activity.getString(R.string.no_memory), Toast.LENGTH_SHORT).show(); + } + } +}*/ + +public class ImageDownloaderAsyncTask extends Thread { + Context mContext; + BaseAdapter mBaseAdapter; + String[] urls = new String[3]; + int index; + + private onImageDownloaderAsyncTaskListener mListener; + + public interface onImageDownloaderAsyncTaskListener { + public void PickDownloadedImage(String path); + } + + public ImageDownloaderAsyncTask( Context context, BaseAdapter baseAdapter, WhatWasHereFragmentGV whatWasHereFragmentGV, String...urls ) { + mContext = context; + mBaseAdapter = baseAdapter; + mListener = whatWasHereFragmentGV; + this.urls[0] = urls[0]; //full url + this.urls[1] = urls[1]; //image name + this.urls[2] = urls[2]; //index of image on grid + this.index = Integer.valueOf( urls[2] ); + } + + @Override + public void run() { + InputStream iStream = null; + String imgUrl = Params.CDN + urls[0]; + Log.d("ImageLoaderTask will download: ", imgUrl ); + URL url; + File tmpFile = null; + try { + File cacheDirectory = ( (Activity) mContext).getCacheDir(); + tmpFile = new File( cacheDirectory.getPath() + "/" + urls[2] + "_" + urls[1] ); + if( true ) { + Log.d("Image was on cache", "no"); + url = new URL(imgUrl); + Bitmap b; + int hw; + Display display = ( (Activity) mContext).getWindowManager().getDefaultDisplay(); + Point size = new Point(); + display.getSize(size); + + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); + urlConnection.connect(); + if( isInterrupted() ) return; + iStream = urlConnection.getInputStream(); + FileOutputStream fOutStream = new FileOutputStream(tmpFile); + hw = size.x / 3; + b = BitmapFactory.decodeStream( iStream ); + b = Bitmap.createScaledBitmap(b, hw, hw, false); + if( isInterrupted() ) return; + b.compress(Bitmap.CompressFormat.JPEG, 90, fOutStream); + fOutStream.flush(); + fOutStream.close(); + }else { + Log.d("Image was on cache", "yes"); + } + HashMap item = new HashMap(); + mListener.PickDownloadedImage( tmpFile.getPath() ); + } catch (Exception e) { + Log.d("Exception on Imagedownloader task", e.getMessage()); + e.printStackTrace(); + } catch ( OutOfMemoryError ome ) { + Log.d("Exception on Imagedownloader task", "OutOfMemoryError"); + } + + } +} \ No newline at end of file diff --git a/whatsup/src/main/java/com/whatsup/whatsup/ImageLoader.java b/whatsup/src/main/java/com/whatsup/whatsup/ImageLoader.java index 354648d..be9294a 100644 --- a/whatsup/src/main/java/com/whatsup/whatsup/ImageLoader.java +++ b/whatsup/src/main/java/com/whatsup/whatsup/ImageLoader.java @@ -50,7 +50,7 @@ public class ImageLoader implements ImageLoaderAsyncTask.OnImageLoaderAsyncTaskL private int mNoLoadedImage; public ImageLoader(int mNoLoadedImage_in) { - mImageLoaderExecutor = Executors.newSingleThreadExecutor(); + mImageLoaderExecutor = Executors.newFixedThreadPool(6); this.mNoLoadedImage = mNoLoadedImage_in; final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. @@ -65,8 +65,6 @@ protected int sizeOf(String key, Bitmap bitmap) { }; } - - public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); } @@ -80,16 +78,17 @@ public void addBitmapToMemoryCache(String key, Bitmap bitmap) { public void getImage( String pathFile_in, int position_in, ViewHolder_GVItem vh_in, Executor pool ) { Bitmap bitmap = null; - bitmap = getBitmapFromMemCache(String.valueOf(position_in)); - if (bitmap != null) { - Log.d("cached", "yes"); - vh_in.icon.setImageBitmap( bitmap ); - } else { - Log.d("cached", "no"); - vh_in.icon.setImageResource( mNoLoadedImage ); - if( pathFile_in != null) - new ImageLoaderAsyncTask( vh_in, position_in, pathFile_in, mImageLoaderExecutor, this ); + bitmap = getBitmapFromMemCache(String.valueOf(position_in)); + if (bitmap != null) { + Log.d("cached", "yes"); + vh_in.icon.setImageBitmap( bitmap ); + } else { + Log.d("cached", "no"); + vh_in.icon.setImageResource( mNoLoadedImage ); + if( pathFile_in != null) { + new ImageLoaderAsyncTask(vh_in, position_in, pathFile_in, mImageLoaderExecutor, this); } + } } } diff --git a/whatsup/src/main/java/com/whatsup/whatsup/WhatWasHereFragmentGV.java b/whatsup/src/main/java/com/whatsup/whatsup/WhatWasHereFragmentGV.java index e0a6ac7..2df0b05 100644 --- a/whatsup/src/main/java/com/whatsup/whatsup/WhatWasHereFragmentGV.java +++ b/whatsup/src/main/java/com/whatsup/whatsup/WhatWasHereFragmentGV.java @@ -48,7 +48,8 @@ * create an instance of this fragment. * */ -public class WhatWasHereFragmentGV extends Fragment { +public class WhatWasHereFragmentGV extends Fragment + implements ImageDownloaderAsyncTask.onImageDownloaderAsyncTaskListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String EVENT_ID = "event_id"; @@ -60,12 +61,10 @@ public class WhatWasHereFragmentGV extends Fragment { private Params parameters; private DownloadTask downloadTask; private ListViewLoaderTask listViewLoaderTask; - private ImageDownloaderTask[] imageLoaderTask; private String data = null; private List> mPictures; - private int mDownloadesPictures = 0; private JSONObject jObject; - private GridView[] gridView; + private GridView gridview; private ImageAdapter imgAdapter; private ExecutorService service; private ExecutorService mImageLoaderPoolThread; @@ -212,6 +211,28 @@ void shutdownAndAwaitTermination(ExecutorService pool) { } } + public void downLoadImage( String path, String imageName, String index ) { + service.submit( new ImageDownloaderAsyncTask( getActivity(), imgAdapter ,this , path, imageName, index ) ); + } + + public void PickDownloadedImage( String path ) { + File file = new File( path ); + String filename = file.getName(); + int index = Integer.valueOf( filename.substring(0, filename.indexOf( "_" ) ) ); + synchronized ( imgAdapter ) { + imgAdapter.setImage( index, path ); + if( index >= gridview.getFirstVisiblePosition() && index <= gridview.getLastVisiblePosition() ) { + Log.d("notified", "yes"); + getActivity().runOnUiThread( new Runnable() { + @Override + public void run() { + imgAdapter.notifyDataSetChanged(); + } + }); + } + } + } + private class PictsJSONparser { //Images processing @@ -280,19 +301,21 @@ protected void onPostExecute(List> pictures) { getView().findViewById(R.id.no_info_not_rellay).setVisibility(View.VISIBLE); } else { imgAdapter = new ImageAdapter(getActivity(), R.layout.fragment_what_was_here_gv_item, pictures.size()); - GridView gridview = (GridView) mWhatWasHereListView.findViewById(R.id.gridview); + gridview = (GridView) mWhatWasHereListView.findViewById(R.id.gridview); getView().findViewById(R.id.loadingPanel).setVisibility(View.GONE); gridview.setAdapter(imgAdapter); gridview.setOnItemClickListener(getImageClickListener()); gridview.setFastScrollEnabled(true); - gridview.setFastScrollAlwaysVisible(false); - service = Executors.newFixedThreadPool(100); + Log.d("adapter", "ready"); + service = Executors.newFixedThreadPool(2); for (int i = 0; i < pictures.size(); i++) { Log.d("new thread for image: ", mPictures.get(i).get("source").toString()); - service.submit( new ImageDownloaderTask(mPictures.get(i).get("source").toString(), + File file = new File( mPictures.get(i).get("source").toString() ); + downLoadImage( mPictures.get(i).get("source").toString(), file.getName(), String.valueOf( i ) ); + /*service.submit( new ImageDownloaderAsyncTask( getActivity(), mPictures.get(i).get("source").toString(), mPictures.get(i).get("source").toString().substring(1, mPictures.get(i).get("source").toString().length()), String.valueOf(i)) - ); + );*/ } } }catch ( NullPointerException e ) { @@ -323,228 +346,9 @@ protected void onPostExecute(String result) { } } } - private class ImageDownloaderTask extends Thread { - String[] urls = new String[3]; - int index; - - public ImageDownloaderTask( String...urls ) { - this.urls[0] = urls[0]; - this.urls[1] = urls[1]; - this.urls[2] = urls[2]; - this.index = Integer.valueOf( urls[2] ); - } - - @Override - public void run() { - InputStream iStream = null; - String imgUrl = Params.CDN + urls[0]; - Log.d("ImageLoaderTask will download: ", imgUrl ); - URL url; - File tmpFile; - try { - File cacheDirectory = getActivity().getCacheDir(); - tmpFile = new File( cacheDirectory.getPath() + "/" + urls[2] + "_" + urls[1] ); - if( true ) { - Log.d("Image was on cache", "no"); - url = new URL(imgUrl); - HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); - urlConnection.connect(); - if( isInterrupted() ) return; - iStream = urlConnection.getInputStream(); - FileOutputStream fOutStream = new FileOutputStream(tmpFile); - Bitmap b = BitmapFactory.decodeStream( iStream ); - b = Bitmap.createScaledBitmap(b, 150, 150, false); - if( isInterrupted() ) return; - b.compress(Bitmap.CompressFormat.JPEG, 70, fOutStream); - fOutStream.flush(); - fOutStream.close(); - }else { - Log.d("Image was on cache", "yes"); - } - HashMap item = new HashMap(); - item.put( "source", tmpFile.getPath() ); - mPictures.set ( Integer.valueOf( urls[2] ) , item); - } catch (Exception e) { - Log.d("Exception on Imagedownloader task", e.getMessage()); - e.printStackTrace(); - } catch ( OutOfMemoryError ome ) { - Toast.makeText( getActivity(), getString( R.string.no_memory ), Toast.LENGTH_SHORT ).show(); - } - synchronized ( imgAdapter ) { - imgAdapter.setImage(index, mPictures.get(index).get("source").toString()); - - } - } - - public 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 = 1; - - 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; - } - } - /* - private class ImageLoaderTask extends AsyncTask { - @Override - protected Integer doInBackground(String... urls) { - InputStream iStream = null; - String imgUrl = Params.CDN + urls[0]; - Log.d("ImageLoaderTask will download: ", imgUrl ); - URL url; - File tmpFile; - try { - File cacheDirectory = getActivity().getCacheDir(); - tmpFile = new File( cacheDirectory.getPath() + "/" + urls[2] + "_" + urls[1] ); - if( !tmpFile.exists() ) { - url = new URL(imgUrl); - HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); - urlConnection.connect(); - iStream = urlConnection.getInputStream(); - FileOutputStream fOutStream = new FileOutputStream(tmpFile); - Bitmap b = BitmapFactory.decodeStream(iStream); - b.compress(Bitmap.CompressFormat.JPEG, 30, fOutStream); - fOutStream.flush(); - fOutStream.close(); - } - HashMap item = new HashMap(); - item.put( "source", tmpFile.getPath() ); - mPictures.set ( Integer.valueOf( urls[2] ) , item); - if (isCancelled()) return null; - } catch (Exception e) { - Log.d("Exception on Imagedownloader task", e.getMessage()); - e.printStackTrace(); - return null; - } catch ( OutOfMemoryError ome ) { - Toast.makeText( getActivity(), getString( R.string.no_memory ), Toast.LENGTH_SHORT ).show(); - } - return Integer.valueOf( urls[2] ); - } - - @Override - protected void onPostExecute(Integer index) { - if( index != null ) { - imgAdapter.setImage( index, mPictures.get( index ).get( "source" ).toString() ); - imgAdapter.notifyDataSetChanged(); - }else { - Toast.makeText(getActivity(), R.string.lost_connection, Toast.LENGTH_SHORT).show(); - } - } - }*/ - - private class ImageAdapter extends BaseAdapter{ - private Context mContext; - private LayoutInflater mInflater; - private int mResourceId; - private int mQuantity; - private int hw; - private HashMap mImages = new HashMap(); - - private static final int PROGRESSBARINDEX = 0; - private static final int IMAGEVIEWINDEX = 1; - - private Handler mHandler; - private ImageLoader mImageLoader = null; - - public ImageAdapter(Context mContext, int resourceId, int quantity) { - this.mContext = mContext; - this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - this.mQuantity = quantity; - this.mResourceId = resourceId; - for( int i=0; i