Complex sorting for search in realm, union of multiple RealmResults

前端 未结 2 505
广开言路
广开言路 2020-12-06 07:51

I replaced sqlite with realm in my open source Linux Command Library project. Everything went fine so far, but now I\'m facing a problem.

I\'m using a RealmBaseAdapt

2条回答
  •  春和景丽
    2020-12-06 08:33

    Not sure if there isn't a better/more-performant way for that but you can try making 3 different queries and then concatenating their results.

        List commands = new ArrayList<>();
    
        commands.addAll(realm.where(Command.class)
                .equalTo("name", query)
                .findAll());
    
        commands.addAll(realm.where(Command.class)
                .beginsWith("name", query)
                .notEqualTo("name", query)
                .findAll());
    
        commands.addAll(realm.where(Command.class)
                .contains("name", query)
                .not().beginsWith("name", query)
                .findAll());
    

    This obviously involves changing your Adapter implementation from RealmBaseAdapter to something more regular. Please keep in mind that while your Realm objects reside in a regular list, they still keep a connection to your Realm database, so you can't close your realm instance while your ListView is displaying data.

    Update: As @EpicPandaForce pointed out in comments, this solution doesn't work well with Realm's autoupdating. It may appear that some Commands are removed / have changed names and this won't be reflected by your Adapter in that case. Make sure to copy your objects first and setup a change listener on your realm results.

提交回复
热议问题