使用Realm数据库的最佳方式

时间:2017-12-05 12:24:15

标签: android database realm android-orm

使用此代码:

public class App extends Application {
            private static App instance;

            @Override
            public void onCreate() {
                super.onCreate();
                initRealmDB();
            }

            private void initRealmDB() {
                instance = this;
                Realm.init(this);
                RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().modules(new SimpleRealmModule()).name("RealmSample.realm").build();
                Realm realm = null;
                try {
                    realm = Realm.getInstance(realmConfiguration);
                    realm.setDefaultConfiguration(realmConfiguration);
                } finally {
                    if (realm != null) {
                        realm.close();
                    }
                }
            }
    }

**In use:**

    Realm realm = Realm.getDefaultInstance();
            RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
            if(realm.isInTransaction())
            {
                realm.cancelTransaction();
            }
            realm.beginTransaction();
            if (results != null) {
                if(membershipList != null)
                {
                    membershipList.clear();
                }
                for (int i = 0; i < results.size(); i++) {
                    Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid());
    }
    }

这是最好的使用方式吗? 我应该使用单身方法吗? 如果还有其他好的方法来完成这项任务,请与我分享。 我跟着这个https://dzone.com/articles/realm-practical-use-in-android 但是此代码不能使用此依赖项:classpath“io.realm:realm-gradle-plugin:3.3.1”

Realm realm = Realm.getInstance(SimpleRealmApp.getInstance());

2 个答案:

答案 0 :(得分:1)

  

这是最好的使用方式吗?

没有

em

相反

Realm realm = Realm.getDefaultInstance(); // <-- opens Realm
        RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
        if(realm.isInTransaction())
        {
            realm.cancelTransaction(); // <-- what if that transaction was important?
        }
        realm.beginTransaction();
        if (results != null) {
            if(membershipList != null)
            {
                membershipList.clear(); // <-- ??
            }
            for (int i = 0; i < results.size(); i++) {
                Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid()); // <-- if the result set was modified here because of the transaction, then the RealmResults will update, and you'll skip elements
}
           // <-- where is the commit?
} // <-- where is realm.close()?
  

我应该使用单身方法吗?

您使用try(Realm r = Realm.getDefaultInstance()) { r.executeTransaction((realm) -> { // AS 3.0+ desugar RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll(); // <-- get in transaction for (OrganizationModelClass model : results) { // uses snapshot() internally Log.i(model.getClass().getName(), getCurrentMembershipUuid()); } } } // <-- auto-close because of try-with-resources / getInstance()打开的Realm实例线程本地和引用计数,因此它不适合在整个应用程序中用作单例。您需要打开线程局部实例。

所以在UI线程上,基于documentation

getDefaultInstance()

对于后台主题,请参阅docs

// Setup Realm in your Application
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
             //.deleteIfMigrationNeeded()
             .migration(new MyMigration())
             .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

// onCreate()/onDestroy() overlap when switching between activities.
// Activity2.onCreate() will be called before Activity1.onDestroy()
// so the call to getDefaultInstance in Activity2 will be fast.
public class MyActivity extends Activity {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        realm = Realm.getDefaultInstance();

        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(this, realm.where(MyModel.class).findAllSortedAsync(MyModelFields.ID)));

        // ...
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

// Use onCreateView()/onDestroyView() for Fragments.
// Note that if the db is large, getting the Realm instance may, briefly, block rendering.
// In that case it may be preferable to manage the Realm instance and RecyclerView from
// onStart/onStop instead. Returning a view, immediately, from onCreateView allows the
// fragment frame to be rendered while the instance is initialized and the view loaded.
public class MyFragment extends Fragment {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        realm = Realm.getDefaultInstance();

        View root = inflater.inflate(R.layout.fragment_view, container, false);

        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(getActivity(), realm.where(MyModel.class).findAllSortedAsync(MyModelFields.ID)));

        // ...

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.close();
    }
}

如果要将Realm用作单例,则必须使用一个可以递增,递减和获取实例的类,而不会增加线程本地领域的引用计数,有点像this experiment here

答案 1 :(得分:0)

public RealmController(Context context) {
    realm = Realm.getDefaultInstance();
}


public static RealmController with(Activity activity) {

    if (instance == null) {
        instance = new RealmController(activity.getApplication());
    }
    return instance;
}


public static RealmController with(Application application) {

    if (instance == null) {
        instance = new RealmController(application);
    }
    return instance;
}

public static RealmController getInstance() {
    if (instance == null) {
        instance = new RealmController(SysApplication.getAppContext());
    }
    return instance;

}
相关问题