使用Realm数据库的最佳方式

问题描述 投票:2回答:2

使用此代码:

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());
android database realm android-orm
2个回答
2
投票

这是最好的使用方式吗?

没有

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() / getDefaultInstance()打开的领域实例是线程本地和引用计数,因此它不适合在整个应用程序中用作单例。您需要打开线程本地实例。

所以在UI Thread上,基于documentation

// 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();
    }
}

有关后台线程,请参阅docs

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try (Realm realm = Realm.getDefaultInstance()) {
            // No need to close the Realm instance manually
        }
    }
});

thread.start();

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


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;

}
© www.soinside.com 2019 - 2024. All rights reserved.