Created
September 3, 2016 14:32
-
-
Save Zhuinden/0d6db32cda696e422a47ed7f9ebf95e9 to your computer and use it in GitHub Desktop.
Realm instance lifecycle per Activity/Fragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SomeActivity extends AppCompatActivity { | |
Realm realm; | |
@Override | |
public void onCreate(Bundle bundle) { | |
super.onCreate(bundle); | |
realm = Realm.getDefaultInstance(); | |
} | |
@Override | |
public void onDestroy() { | |
super.onDestroy(); | |
if(realm != null) { // guard against weird low-budget phones | |
realm.close(); | |
realm = null; | |
} | |
} | |
} | |
public class SomeFragment extends Fragment { | |
Realm realm; | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle) { | |
realm = Realm.getDefaultInstance(); | |
View view = //... inflate and stuff | |
return view; | |
} | |
@Override | |
public void onDestroyView() { | |
super.onDestroyView(); | |
if(realm != null) { | |
realm.close(); | |
realm = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment