Skip to content

Instantly share code, notes, and snippets.

@mths0x5f
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save mths0x5f/aef09db983810325c6d9 to your computer and use it in GitHub Desktop.

Select an option

Save mths0x5f/aef09db983810325c6d9 to your computer and use it in GitHub Desktop.
Using a Fragment to retain object instances on device configuration changes - Android
/*
* Created on base of this tutorial:
* http://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject
* Licensed under Apache License 2.0, as the Official Android Documentation
*
*/
package com.example.myapplication.util;
import android.app.Fragment;
import android.os.Bundle;
/**
* This class makes preserving object instances on configuration change easy
* @param <T> Generic type of the object
*/
public class DataFragment<T> extends Fragment {
private T data;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public void setData(T data) { this.data = data; }
public T getData() { return data; }
}
@mths0x5f
Copy link
Author

An important note from documentation:

Caution: While you can store any object, you should never pass an object that is tied to the Activity, such as a Drawable, an Adapter, a View or any other object that's associated with a Context. If you do, it will leak all the views and resources of the original activity instance. (Leaking resources means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment