Reputation: 3667
I have the following method which has an ImageSwitcher that the user can slide left and right. The selected image is displayed in the center of the screen. I've done some image scaling for high res images on low memory phones, but I still run into Bitmap OutOfMemoryEexception when sliding quickly left to right. I'd like to transform the line mSwitcher.setImageURI(myUri);
(This is the line that is causing the OOME) to use a weak reference, so that it can be automatically garbage collected. How can I do this? Is this the best way to performance optimize this method?
Thanks
method:
public void onItemSelected(AdapterView parent, View v, int position, long id) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyAppName");
File[] cachedOnSDImages = mediaStorageDir.listFiles();
countArray = new Integer[cachedOnSDImages.length];
fileArray = new String[cachedOnSDImages.length];
fileArray[position] = cachedOnSDImages[position].getAbsolutePath();
Uri myUri = Uri.parse(fileArray[position]);
mSwitcher.setImageURI(myUri); // weakly reference myUri in this line
this.currentpos = position;
}
I should add the mSwitcher is instantiated here:
private void makeSwitcher() {
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
}
Upvotes: 3
Views: 5165
Reputation: 1943
import java.lang.ref.WeakReference;
public class ReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference r = new WeakReference(new String("I'm here"));
WeakReference sr = new WeakReference("I'm here");
System.out.println("before gc: r=" + r.get() + ", static=" + sr.get());
System.gc();
Thread.sleep(100);
// only r.get() becomes null
System.out.println("after gc: r=" + r.get() + ", static=" + sr.get());
}
}
Taken from wiki Weak references
This is how Weak references can be used in Java - however this also means that it will not work in your case since switcher would have to explicitly accept a WeakReference Object instead of a URI.
Upvotes: 5