Browse Source

Merge pull request #955 from owncloud/thumbnailOOM

HOTFIX: prevent OOM when scrolling Thumbnails
masensio 10 years ago
parent
commit
288c148b51

+ 4 - 3
res/layout/preview_image_fragment.xml

@@ -29,8 +29,8 @@
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/top"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
     android:background="#000000"
     tools:context=".ui.fragment.PreviewImageFragment" >
 
@@ -57,9 +57,10 @@
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
-        android:layout_below="@id/image"
+        android:layout_alignParentBottom="true"
         android:layout_margin="40dp"
         android:text="@string/placeholder_sentence"
+        android:textColor="@color/owncloud_blue_bright"
         />
     
 </RelativeLayout>

+ 1 - 0
res/values/strings.xml

@@ -334,5 +334,6 @@
 
     <string name="auth_refresh_button">Refresh connection</string>
     <string name="auth_host_address">Server address</string>
+    <string name="common_error_out_memory">Not enough memory</string>
 
 </resources>

+ 6 - 3
src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java

@@ -22,6 +22,7 @@
 package com.owncloud.android.datamodel;
 
 import java.io.File;
+import java.io.InputStream;
 import java.lang.ref.WeakReference;
 
 import org.apache.commons.httpclient.HttpStatus;
@@ -290,9 +291,11 @@ public class ThumbnailsCacheManager {
                                 GetMethod get = new GetMethod(uri);
                                 status = mClient.executeMethod(get);
                                 if (status == HttpStatus.SC_OK) {
-                                    byte[] bytes = get.getResponseBody();
-                                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
-                                            bytes.length);
+//                                    byte[] bytes = get.getResponseBody();
+//                                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
+//                                            bytes.length);
+                                    InputStream inputStream = get.getResponseBodyAsStream();
+                                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                     thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
 
                                     // Add thumbnail to cache

+ 16 - 11
src/com/owncloud/android/ui/adapter/FileListListAdapter.java

@@ -158,17 +158,22 @@ public class FileListListAdapter extends BaseAdapter implements ListAdapter {
             viewType = ViewType.GRID_ITEM;
         }
 
-        // Create View
-        switch (viewType){
-            case GRID_IMAGE:
-                view = inflator.inflate(R.layout.grid_image, null);
-                break;
-            case GRID_ITEM:
-                view = inflator.inflate(R.layout.grid_item, null);
-                break;
-            case LIST_ITEM:
-                view = inflator.inflate(R.layout.list_item, null);
-                break;
+        // create view only if differs, otherwise reuse
+        if (convertView == null || (convertView != null && convertView.getTag() != viewType)) {
+            switch (viewType) {
+                case GRID_IMAGE:
+                    view = inflator.inflate(R.layout.grid_image, null);
+                    view.setTag(ViewType.GRID_IMAGE);
+                    break;
+                case GRID_ITEM:
+                    view = inflator.inflate(R.layout.grid_item, null);
+                    view.setTag(ViewType.GRID_ITEM);
+                    break;
+                case LIST_ITEM:
+                    view = inflator.inflate(R.layout.list_item, null);
+                    view.setTag(ViewType.LIST_ITEM);
+                    break;
+            }
         }
 
         view.invalidate();

+ 55 - 58
src/com/owncloud/android/ui/preview/FileDownloadFragment.java

@@ -23,18 +23,16 @@ import java.lang.ref.WeakReference;
 
 import com.owncloud.android.R;
 import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
 import com.owncloud.android.ui.fragment.FileFragment;
 
 import android.accounts.Account;
 import android.os.Bundle;
+import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentStatePagerAdapter;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup;
-import android.widget.ImageButton;
-import android.widget.LinearLayout;
 import android.widget.ProgressBar;
 import android.widget.TextView;
 
@@ -50,10 +48,14 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
     public static final String EXTRA_FILE = "FILE";
     public static final String EXTRA_ACCOUNT = "ACCOUNT";
     private static final String EXTRA_ERROR = "ERROR";
+    
+    private static final String ARG_FILE = "FILE";
+    private static final String ARG_IGNORE_FIRST = "IGNORE_FIRST";
+    private static final String ARG_ACCOUNT = "ACCOUNT" ;
 
     private View mView;
     private Account mAccount;
-    
+
     public ProgressListener mProgressListener;
     private boolean mListening;
     
@@ -61,12 +63,39 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
     
     private boolean mIgnoreFirstSavedState;
     private boolean mError;
-    
+
+
+    /**
+     * Public factory method to create a new fragment that shows the progress of a file download.
+     *
+     * Android strongly recommends keep the empty constructor of fragments as the only public constructor, and
+     * use {@link #setArguments(Bundle)} to set the needed arguments.
+     *
+     * This method hides to client objects the need of doing the construction in two steps.
+     *
+     * When 'file' is null creates a dummy layout (useful when a file wasn't tapped before).
+     *
+     * @param file                      An {@link OCFile} to show in the fragment
+     * @param account                   An OC account; needed to start downloads
+     * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}
+     *                                  TODO better solution
+     */
+    public static Fragment newInstance(OCFile file, Account account, boolean ignoreFirstSavedState) {
+        FileDownloadFragment frag = new FileDownloadFragment();
+        Bundle args = new Bundle();
+        args.putParcelable(ARG_FILE, file);
+        args.putParcelable(ARG_ACCOUNT, account);
+        args.putBoolean(ARG_IGNORE_FIRST, ignoreFirstSavedState);
+        frag.setArguments(args);
+        return frag;
+    }
+
 
     /**
      * Creates an empty details fragment.
      * 
-     * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically. 
+     * It's necessary to keep a public constructor without parameters; the system uses it when tries to
+     * reinstantiate a fragment automatically.
      */
     public FileDownloadFragment() {
         super();
@@ -76,30 +105,17 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
         mIgnoreFirstSavedState = false;
         mError = false;
     }
-    
-    
-    /**
-     * Creates a details fragment.
-     * 
-     * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
-     * 
-     * @param fileToDetail      An {@link OCFile} to show in the fragment
-     * @param ocAccount         An ownCloud account; needed to start downloads
-     * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution 
-     */
-    public FileDownloadFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
-        super(fileToDetail);
-        mAccount = ocAccount;
-        mProgressListener = null;
-        mListening = false;
-        mIgnoreFirstSavedState = ignoreFirstSavedState;
-        mError = false;
-    }
-    
-    
+
+
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        Bundle args = getArguments();
+        setFile((OCFile)args.getParcelable(ARG_FILE));
+            // TODO better in super, but needs to check ALL the class extending FileFragment; not right now
+
+        mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
+        mAccount = args.getParcelable(ARG_ACCOUNT);
     }
     
 
@@ -125,9 +141,9 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
         ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.progressBar);
         mProgressListener = new ProgressListener(progressBar);
         
-        ((ImageButton)mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
+        (mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
         
-        ((LinearLayout)mView.findViewById(R.id.fileDownloadLL)).setOnClickListener(new OnClickListener() {
+        (mView.findViewById(R.id.fileDownloadLL)).setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View v) {
                 ((PreviewImageActivity) getActivity()).toggleFullScreen();
@@ -205,31 +221,6 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
     }
 
     
-    /**
-     * Updates the view depending upon the state of the downloading file.
-     * 
-     * @param   transferring    When true, the view must be updated assuming that the holded file is 
-     *                          downloading, no matter what the downloaderBinder says.
-     */
-    /*
-    public void updateView(boolean transferring) {
-        // configure UI for depending upon local state of the file
-        // TODO remove
-        if (transferring || getFile().isDownloading()) {
-            setButtonsForTransferring();
-            
-        } else if (getFile().isDown()) {
-            
-            setButtonsForDown();
-            
-        } else {
-            setButtonsForRemote();
-        }
-        getView().invalidate();
-        
-    }
-    */
-
     /**
      * Enables or disables buttons for a file being downloaded
      */
@@ -289,7 +280,9 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
     public void listenForTransferProgress() {
         if (mProgressListener != null && !mListening) {
             if (mContainerActivity.getFileDownloaderBinder() != null) {
-                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
+                mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(
+                        mProgressListener, mAccount, getFile()
+                );
                 mListening = true;
                 setButtonsForTransferring();
             }
@@ -300,13 +293,15 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
     public void leaveTransferProgress() {
         if (mProgressListener != null) {
             if (mContainerActivity.getFileDownloaderBinder() != null) {
-                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
+                mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(
+                        mProgressListener, mAccount, getFile()
+                );
                 mListening = false;
             }
         }
     }
 
-    
+
     /**
      * Helper class responsible for updating the progress bar shown for file uploading or downloading
      */
@@ -319,7 +314,9 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
         }
         
         @Override
-        public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
+        public void onTransferProgress(
+                long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename
+        ) {
             int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
             if (percent != mLastPercent) {
                 ProgressBar pb = mProgressBar.get();

+ 28 - 15
src/com/owncloud/android/ui/preview/ImageViewCustom.java

@@ -12,10 +12,16 @@ import android.widget.ImageView;
 import com.owncloud.android.lib.common.utils.Log_OC;
 
 public class ImageViewCustom extends ImageView {
-    
+
+    private static final String TAG = ImageViewCustom.class.getSimpleName();
+
     private static final boolean IS_ICS_OR_HIGHER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
-    
-    private Bitmap mBitmap;
+    private static final boolean IS_VERSION_BUGGY_ON_RECYCLES =
+            Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1 ||
+            Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2;
+
+    private int mBitmapHeight;
+    private int mBitmapWidth;
 
     
     public ImageViewCustom(Context context) {
@@ -34,9 +40,13 @@ public class ImageViewCustom extends ImageView {
 	@Override
     protected void onDraw(Canvas canvas) {
 
-        if(IS_ICS_OR_HIGHER && checkIfMaximumBitmapExceed(canvas)) {
-            // Set layer type to software one for avoiding exceed
-            // and problems in visualization
+        if(IS_ICS_OR_HIGHER && checkIfMaximumBitmapExceed(canvas) || IS_VERSION_BUGGY_ON_RECYCLES ) {
+            // Software type is set with two targets:
+            // 1. prevent that bitmaps larger than maximum textures allowed are shown as black views in devices
+            //  with LAYER_TYPE_HARDWARE enabled by default;
+            // 2. grant that bitmaps are correctly dellocated from memory in versions suffering the bug fixed in
+            //  https://android.googlesource.com/platform/frameworks/base/+/034de6b1ec561797a2422314e6ef03e3cd3e08e0;
+            //
             setLayerType(View.LAYER_TYPE_SOFTWARE, null);
         }
 
@@ -45,26 +55,29 @@ public class ImageViewCustom extends ImageView {
 
     /**
      * Checks if current bitmaps exceed the maximum OpenGL texture size limit
-     * @param bitmap
-     * @return boolean
+     * @param canvas        Canvas where the view will be drawn into.
+     * @return boolean      True means that the bitmap is too big for the canvas.
      */
     @SuppressLint("NewApi")
 	private boolean checkIfMaximumBitmapExceed(Canvas canvas) {
-        Log_OC.d("OC", "Canvas maximum: " + canvas.getMaximumBitmapWidth() + " - " + canvas.getMaximumBitmapHeight());
-        if (mBitmap!= null && (mBitmap.getWidth() > canvas.getMaximumBitmapWidth() 
-                || mBitmap.getHeight() > canvas.getMaximumBitmapHeight())) {
+        Log_OC.v(TAG, "Canvas maximum: " + canvas.getMaximumBitmapWidth() + " - " + canvas.getMaximumBitmapHeight());
+        if (mBitmapWidth > canvas.getMaximumBitmapWidth()
+                || mBitmapHeight > canvas.getMaximumBitmapHeight()) {
             return true;
         }
         
         return false;
     }
     
+    @Override
     /**
-     * Set current bitmap
-     * @param bitmap
+     * Keeps the size of the bitmap cached in member variables for faster access in {@link #onDraw(Canvas)} ,
+     * but without keeping another reference to the {@link Bitmap}
      */
-    public void setBitmap (Bitmap bitmap) {
-        mBitmap = bitmap;
+    public void setImageBitmap (Bitmap bm) {
+        mBitmapWidth = bm.getWidth();
+        mBitmapHeight = bm.getHeight();
+        super.setImageBitmap(bm);
     }
 
 }

+ 114 - 193
src/com/owncloud/android/ui/preview/PreviewImageFragment.java

@@ -19,25 +19,16 @@
  */
 package com.owncloud.android.ui.preview;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
 import java.lang.ref.WeakReference;
 
 import android.accounts.Account;
 import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.BitmapFactory.Options;
 import android.graphics.Point;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.support.v4.app.FragmentStatePagerAdapter;
-import android.view.Display;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
@@ -57,6 +48,7 @@ import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
 import com.owncloud.android.ui.fragment.FileFragment;
 import com.owncloud.android.utils.BitmapUtils;
+import com.owncloud.android.utils.DisplayUtils;
 
 import third_parties.michaelOrtiz.TouchImageViewCustom;
 
@@ -64,17 +56,17 @@ import third_parties.michaelOrtiz.TouchImageViewCustom;
 /**
  * This fragment shows a preview of a downloaded image.
  * 
- * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
+ * Trying to get an instance with a NULL {@link OCFile} will produce an {@link IllegalStateException}.
  * 
  * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
  */
 public class PreviewImageFragment extends FileFragment {
 
     public static final String EXTRA_FILE = "FILE";
-    public static final String EXTRA_ACCOUNT = "ACCOUNT";
 
-    private View mView;
-    private Account mAccount;
+    private static final String ARG_FILE = "FILE";
+    private static final String ARG_IGNORE_FIRST = "IGNORE_FIRST";
+
     private TouchImageViewCustom mImageView;
     private TextView mMessageView;
     private ProgressBar mProgressWheel;
@@ -87,33 +79,39 @@ public class PreviewImageFragment extends FileFragment {
     
     private LoadBitmapTask mLoadBitmapTask = null;
 
-    
+
     /**
-     * Creates a fragment to preview an image.
-     * 
-     * When 'imageFile' or 'ocAccount' are null
-     * 
+     * Public factory method to create a new fragment that previews an image.
+     *
+     * Android strongly recommends keep the empty constructor of fragments as the only public constructor, and
+     * use {@link #setArguments(Bundle)} to set the needed arguments.
+     *
+     * This method hides to client objects the need of doing the construction in two steps.
+     *
      * @param imageFile                 An {@link OCFile} to preview as an image in the fragment
-     * @param ocAccount                 An ownCloud account; needed to start downloads
-     * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution 
+     * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}
+     *                                  ; TODO better solution
      */
-    public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
-        super(fileToDetail);
-        mAccount = ocAccount;
-        mIgnoreFirstSavedState = ignoreFirstSavedState;
+    public static PreviewImageFragment newInstance(OCFile imageFile, boolean ignoreFirstSavedState) {
+        PreviewImageFragment frag = new PreviewImageFragment();
+        Bundle args = new Bundle();
+        args.putParcelable(ARG_FILE, imageFile);
+        args.putBoolean(ARG_IGNORE_FIRST, ignoreFirstSavedState);
+        frag.setArguments(args);
+        return frag;
     }
+
     
     
     /**
      *  Creates an empty fragment for image previews.
      * 
-     *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
+     *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
+     *  (for instance, when the device is turned a aside).
      * 
      *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction 
      */
     public PreviewImageFragment() {
-        super();
-        mAccount = null;
         mIgnoreFirstSavedState = false;
     }
     
@@ -124,6 +122,11 @@ public class PreviewImageFragment extends FileFragment {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        Bundle args = getArguments();
+        setFile((OCFile)args.getParcelable(ARG_FILE));
+            // TODO better in super, but needs to check ALL the class extending FileFragment; not right now
+
+        mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
         setHasOptionsMenu(true);
     }
     
@@ -135,8 +138,8 @@ public class PreviewImageFragment extends FileFragment {
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
         super.onCreateView(inflater, container, savedInstanceState);
-        mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
-        mImageView = (TouchImageViewCustom) mView.findViewById(R.id.image);
+        View view = inflater.inflate(R.layout.preview_image_fragment, container, false);
+        mImageView = (TouchImageViewCustom) view.findViewById(R.id.image);
         mImageView.setVisibility(View.GONE);
         mImageView.setOnClickListener(new OnClickListener() {
             @Override
@@ -145,11 +148,11 @@ public class PreviewImageFragment extends FileFragment {
             }
 
         });
-        mMessageView = (TextView)mView.findViewById(R.id.message);
+        mMessageView = (TextView)view.findViewById(R.id.message);
         mMessageView.setVisibility(View.GONE);
-        mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
+        mProgressWheel = (ProgressBar)view.findViewById(R.id.progressWheel);
         mProgressWheel.setVisibility(View.VISIBLE);
-        return mView;
+        return view;
     }
 
     /**
@@ -160,9 +163,8 @@ public class PreviewImageFragment extends FileFragment {
         super.onActivityCreated(savedInstanceState);
         if (savedInstanceState != null) {
             if (!mIgnoreFirstSavedState) {
-                OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
+                OCFile file = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
                 setFile(file);
-                mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
             } else {
                 mIgnoreFirstSavedState = false;
             }
@@ -170,9 +172,6 @@ public class PreviewImageFragment extends FileFragment {
         if (getFile() == null) {
             throw new IllegalStateException("Instanced with a NULL OCFile");
         }
-        if (mAccount == null) {
-            throw new IllegalStateException("Instanced with a NULL ownCloud Account");
-        }
         if (!getFile().isDown()) {
             throw new IllegalStateException("There is no local file to preview");
         }
@@ -186,7 +185,6 @@ public class PreviewImageFragment extends FileFragment {
     public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
         outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
-        outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
     }
     
 
@@ -194,20 +192,21 @@ public class PreviewImageFragment extends FileFragment {
     public void onStart() {
         super.onStart();
         if (getFile() != null) {
-           mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
-           mLoadBitmapTask.execute(new String[]{getFile().getStoragePath()});
+            mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
+            //mLoadBitmapTask.execute(new String[]{getFile().getStoragePath()});
+            mLoadBitmapTask.execute(getFile().getStoragePath());
         }
     }
     
     
     @Override
     public void onStop() {
-        super.onStop();
+        Log_OC.d(TAG, "onStop starts");
         if (mLoadBitmapTask != null) {
             mLoadBitmapTask.cancel(true);
             mLoadBitmapTask = null;
         }
-        
+        super.onStop();
     }
     
     /**
@@ -329,6 +328,9 @@ public class PreviewImageFragment extends FileFragment {
         if (mBitmap != null) {
             mBitmap.recycle();
             System.gc();
+                // putting this in onStop() is just the same; the fragment is always destroyed by
+                // {@link FragmentStatePagerAdapter} when the fragment in swiped further than the valid offscreen
+                // distance, and onStop() is never called before than that
         }
         super.onDestroy();
     }
@@ -348,20 +350,22 @@ public class PreviewImageFragment extends FileFragment {
         /**
          * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
          * 
-         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
+         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before
+         * the load finishes.
          */
         private final WeakReference<ImageViewCustom> mImageViewRef;
 
         /**
          * Weak reference to the target {@link TextView} where error messages will be written.
          * 
-         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
+         * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the
+         * load finishes.
          */
         private final WeakReference<TextView> mMessageViewRef;
 
         
         /**
-         * Weak reference to the target {@link Progressbar} shown while the load is in progress.
+         * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
          * 
          * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
          */
@@ -389,47 +393,47 @@ public class PreviewImageFragment extends FileFragment {
         @Override
         protected Bitmap doInBackground(String... params) {
             Bitmap result = null;
-            if (params.length != 1) return result;
+            if (params.length != 1) return null;
             String storagePath = params[0];
             try {
 
-                if (isCancelled()) return result;
-                
-                File picture = new File(storagePath);
-
-                if (picture != null) {
-                    // Decode file into a bitmap in real size for being able to make zoom on 
-                    // the image
-                    result = BitmapFactory.decodeStream(new FlushedInputStream
-                            (new BufferedInputStream(new FileInputStream(picture))));
-                }
-
-                if (isCancelled()) return result;
-                
-                if (result == null) {
-                    mErrorMessageId = R.string.preview_image_error_unknown_format;
-                    Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
-                } else {
-                    // Rotate image, obeying exif tag.
-                    result = BitmapUtils.rotateImage(result, storagePath);
+                int maxDownScale = 3;   // could be a parameter passed to doInBackground(...)
+                Point screenSize = DisplayUtils.getScreenSize(getActivity());
+                int minWidth = screenSize.x;
+                int minHeight = screenSize.y;
+                for (int i = 0; i < maxDownScale && result == null; i++) {
+                    if (isCancelled()) return null;
+                    try {
+                        result = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth, minHeight);
+
+                        if (isCancelled()) return result;
+
+                        if (result == null) {
+                            mErrorMessageId = R.string.preview_image_error_unknown_format;
+                            Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
+                            break;
+                        } else {
+                            // Rotate image, obeying exif tag.
+                            result = BitmapUtils.rotateImage(result, storagePath);
+                        }
+
+                    } catch (OutOfMemoryError e) {
+                        mErrorMessageId = R.string.common_error_out_memory;
+                        if (i < maxDownScale - 1) {
+                            Log_OC.w(TAG, "Out of memory rendering file " + storagePath + " ; scaling down");
+                            minWidth = minWidth / 2;
+                            minHeight = minHeight / 2;
+
+                        } else {
+                            Log_OC.w(TAG, "Out of memory rendering file " + storagePath + " ; failing");
+                        }
+                        if (result != null) {
+                            result.recycle();
+                        }
+                        result = null;
+                    }
                 }
-                
-            } catch (OutOfMemoryError e) {
-                Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
 
-                if (isCancelled()) return result;
-                
-                // If out of memory error when loading or rotating image, try to load it scaled
-                result = loadScaledImage(storagePath);
-
-                if (result == null) {
-                    mErrorMessageId = R.string.preview_image_error_unknown_format;
-                    Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
-                } else {
-                    // Rotate scaled image, obeying exif tag
-                    result = BitmapUtils.rotateImage(result, storagePath);
-                }
-                    
             } catch (NoSuchFieldError e) {
                 mErrorMessageId = R.string.common_error_unknown;
                 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " 
@@ -459,50 +463,46 @@ public class PreviewImageFragment extends FileFragment {
             } else {
                 showErrorMessage();
             }
+            if (result != null && mBitmap != result)  {
+                // unused bitmap, release it! (just in case)
+                result.recycle();
+            }
         }
         
         @SuppressLint("InlinedApi")
         private void showLoadedImage(Bitmap result) {
-            if (mImageViewRef != null) {
-                final ImageViewCustom imageView = mImageViewRef.get();
-                if (imageView != null) {
-                    imageView.setBitmap(result);
-                    imageView.setImageBitmap(result);
-                    imageView.setVisibility(View.VISIBLE);
-                    mBitmap  = result;
-                } // else , silently finish, the fragment was destroyed
-            }
-            if (mMessageViewRef != null) {
-                final TextView messageView = mMessageViewRef.get();
-                if (messageView != null) {
-                    messageView.setVisibility(View.GONE);
-                } // else , silently finish, the fragment was destroyed
+            final ImageViewCustom imageView = mImageViewRef.get();
+            if (imageView != null) {
+                Log_OC.d(TAG, "Showing image with resolution " + result.getWidth() + "x" + result.getHeight());
+                imageView.setImageBitmap(result);
+                imageView.setVisibility(View.VISIBLE);
+                mBitmap  = result;  // needs to be kept for recycling when not useful
             }
+
+            final TextView messageView = mMessageViewRef.get();
+            if (messageView != null) {
+                messageView.setVisibility(View.GONE);
+            } // else , silently finish, the fragment was destroyed
         }
         
         private void showErrorMessage() {
-            if (mImageViewRef != null) {
-                final ImageView imageView = mImageViewRef.get();
-                if (imageView != null) {
-                    // shows the default error icon
-                    imageView.setVisibility(View.VISIBLE);
-                } // else , silently finish, the fragment was destroyed
-            }
-            if (mMessageViewRef != null) {
-                final TextView messageView = mMessageViewRef.get();
-                if (messageView != null) {
-                    messageView.setText(mErrorMessageId);
-                    messageView.setVisibility(View.VISIBLE);
-                } // else , silently finish, the fragment was destroyed
-            }
+            final ImageView imageView = mImageViewRef.get();
+            if (imageView != null) {
+                // shows the default error icon
+                imageView.setVisibility(View.VISIBLE);
+            } // else , silently finish, the fragment was destroyed
+
+            final TextView messageView = mMessageViewRef.get();
+            if (messageView != null) {
+                messageView.setText(mErrorMessageId);
+                messageView.setVisibility(View.VISIBLE);
+            } // else , silently finish, the fragment was destroyed
         }
         
         private void hideProgressWheel() {
-            if (mProgressWheelRef != null) {
-                final ProgressBar progressWheel = mProgressWheelRef.get();
-                if (progressWheel != null) {
-                    progressWheel.setVisibility(View.GONE);
-                }
+            final ProgressBar progressWheel = mProgressWheelRef.get();
+            if (progressWheel != null) {
+                progressWheel.setVisibility(View.GONE);
             }
         }
         
@@ -531,83 +531,4 @@ public class PreviewImageFragment extends FileFragment {
         return mImageView;
     }
 
-    static class FlushedInputStream extends FilterInputStream {
-        public FlushedInputStream(InputStream inputStream) {
-        super(inputStream);
-        }
-
-        @Override
-        public long skip(long n) throws IOException {
-            long totalBytesSkipped = 0L;
-            while (totalBytesSkipped < n) {
-                long bytesSkipped = in.skip(n - totalBytesSkipped);
-                if (bytesSkipped == 0L) {
-                      int byteValue = read();
-                      if (byteValue < 0) {
-                          break;  // we reached EOF
-                      } else {
-                          bytesSkipped = 1; // we read one byte
-                      }
-               }
-               totalBytesSkipped += bytesSkipped;
-            }
-            return totalBytesSkipped;
-        }
-    }
-
-    /**
-     * Load image scaled
-     * @param storagePath: path of the image
-     * @return Bitmap
-     */
-    @SuppressWarnings("deprecation")
-    private Bitmap loadScaledImage(String storagePath) {
-
-        Log_OC.d(TAG, "Loading image scaled");
-
-        // set desired options that will affect the size of the bitmap
-        BitmapFactory.Options options = new Options();
-        options.inScaled = true;
-        options.inPurgeable = true;
-        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
-            options.inPreferQualityOverSpeed = false;
-        }
-        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
-            options.inMutable = false;
-        }
-        // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
-        options.inJustDecodeBounds = true;
-        BitmapFactory.decodeFile(storagePath, options);
-
-        int width = options.outWidth;
-        int height = options.outHeight;
-        int scale = 1;
-
-        Display display = getActivity().getWindowManager().getDefaultDisplay();
-        Point size = new Point();
-        int screenWidth;
-        int screenHeight;
-        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
-            display.getSize(size);
-            screenWidth = size.x;
-            screenHeight = size.y;
-        } else {
-            screenWidth = display.getWidth();
-            screenHeight = display.getHeight();
-        }
-
-        if (width > screenWidth) {
-            // second try to scale down the image , this time depending upon the screen size 
-            scale = (int) Math.floor((float)width / screenWidth);
-        }
-        if (height > screenHeight) {
-            scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
-        }
-        options.inSampleSize = scale;
-
-        // really load the bitmap
-        options.inJustDecodeBounds = false; // the next decodeFile call will be real
-        return BitmapFactory.decodeFile(storagePath, options);
-
-    }
 }

+ 5 - 3
src/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.java

@@ -102,15 +102,17 @@ public class PreviewImagePagerAdapter extends FragmentStatePagerAdapter {
         OCFile file = mImageFiles.get(i);
         Fragment fragment = null;
         if (file.isDown()) {
-            fragment = new PreviewImageFragment(file, mAccount, mObsoletePositions.contains(Integer.valueOf(i)));
+            fragment = PreviewImageFragment.newInstance(file, mObsoletePositions.contains(Integer.valueOf(i)));
             
         } else if (mDownloadErrors.contains(Integer.valueOf(i))) {
-            fragment = new FileDownloadFragment(file, mAccount, true);
+            fragment = FileDownloadFragment.newInstance(file, mAccount, true);
             ((FileDownloadFragment)fragment).setError(true);
             mDownloadErrors.remove(Integer.valueOf(i));
             
         } else {
-            fragment = new FileDownloadFragment(file, mAccount, mObsoletePositions.contains(Integer.valueOf(i)));
+            fragment = FileDownloadFragment.newInstance(
+                    file, mAccount, mObsoletePositions.contains(Integer.valueOf(i))
+            );
         }
         mObsoletePositions.remove(Integer.valueOf(i));
         return fragment;

+ 3 - 1
src/com/owncloud/android/utils/BitmapUtils.java

@@ -95,7 +95,9 @@ public class BitmapUtils {
         if (height > reqHeight || width > reqWidth) {
             final int halfHeight = height / 2;
             final int halfWidth = width / 2;
-    
+
+            // calculates the largest inSampleSize value (for smallest sample) 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;

+ 23 - 0
src/com/owncloud/android/utils/DisplayUtils.java

@@ -33,9 +33,12 @@ import java.util.Set;
 import java.util.Vector;
 
 import android.annotation.TargetApi;
+import android.app.Activity;
 import android.content.Context;
+import android.graphics.Point;
 import android.os.Build;
 import android.text.format.DateUtils;
+import android.view.Display;
 import android.webkit.MimeTypeMap;
 
 import com.owncloud.android.MainApp;
@@ -350,4 +353,24 @@ public class DisplayUtils {
         return path;
     }
 
+
+    /**
+     * Gets the screen size in pixels in a backwards compatible way
+     *
+     * @param caller        Activity calling; needed to get access to the {@link android.view.WindowManager}
+     * @return              Size in pixels of the screen, or default {@link Point} if caller is null
+     */
+    public static Point getScreenSize(Activity caller) {
+        Point size = new Point();
+        if (caller != null) {
+            Display display = caller.getWindowManager().getDefaultDisplay();
+            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
+                display.getSize(size);
+            } else {
+                size.set(display.getWidth(), display.getHeight());
+            }
+        }
+        return size;
+    }
+
 }