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());
4

2 回答 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 线程上,基于文档

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

对于后台线程,请参阅文档

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 用作单例,则必须使用一个可以递增、递减和获取实例的类,而无需增加线程本地 Realms 的引用计数,有点像这里的这个实验

于 2017-12-05T12:51:54.140 回答
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;

}
于 2019-03-08T20:12:33.663 回答