當片段的活動擴展了控制領域的基本活動時,我很困惑如何處理片段中的Realm。導致NullPointerException的片段中的領域
換句話說,我有這樣的結構:
Base Activity -> User Activity -> Base Fragment -> Fragment
一切工作正常,直到我退出活動(即回到以前的活動)。我得到這個錯誤:
java.lang.RuntimeException: Unable to destroy activity {UserActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void io.realm.Realm.close()' on a null object reference
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void io.realm.Realm.close()' on a null object reference at BaseFragment.onDestroyView
我的基本活動:
public abstract class BaseActivity extends AppCompatActivity {
private Realm realm;
protected abstract int getLayoutResource();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
realm = Realm.getDefaultInstance();
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
public Realm getRealm() {
return realm;
}
}
我的主要活動(其中創建的片段):
public class UserActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String type = getIntent().getStringExtra("type");
Fragment fragment = null;
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
if (type.equals("first")) {
fragment = new FirstFragment();
} else if (type.equals("second")) {
fragment = new SecondFragment();
}
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment).commit();
}
}
@Override
protected int getLayoutResource() {
return R.layout.activity_user;
}
}
我所有的碎片的擴展基本片段。這裏是我的基片段:
public abstract class BaseFragment extends Fragment {
private Realm realm;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
realm = Realm.getDefaultInstance();
return inflater.inflate(getFragmentLayout(), container, false);
}
@Override
public void onDestroyView() {
super.onDestroyView();
realm.close();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// some realm operation
}
});
}
protected abstract int getFragmentLayout();
}
是什麼原因導致了這個問題?我是否正確管理Realm?
嘗試在超級方法之前放置realm.close()調用? – aProperFox
仍然導致NPE不幸。 :/ – user656217