Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Created September 3, 2016 14:32
Show Gist options
  • Save Zhuinden/0d6db32cda696e422a47ed7f9ebf95e9 to your computer and use it in GitHub Desktop.
Save Zhuinden/0d6db32cda696e422a47ed7f9ebf95e9 to your computer and use it in GitHub Desktop.
Realm instance lifecycle per Activity/Fragment
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