Search code examples
androiddatabasemongodbasynchronousrealm

Android MongoDB Realm: Skipped 28 frames! The application may be doing too much work on its main thread


I am having this problem even though I used async in Realm. The lag is very noticeable. Is there something wrong with how I code it? This is my code:

    RealmConfiguration configuration = new RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            .build();

    realm = Realm.getInstance(configuration);

    itemCategoryName = getIntent().getExtras().getString("category", "");
    itemCategoryName = itemCategoryName.toLowerCase();

    shopItemList = new ArrayList<>();

    shopItemAdapter = new ShopItemAdapter(this, shopItemList);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    recyclerView.setAdapter(shopItemAdapter);


    realm.where(ShopItem.class).contains("category", itemCategoryName, Case.INSENSITIVE).findAllAsync()
    .addChangeListener(new RealmChangeListener<RealmResults<ShopItem>>() {
        @Override
        public void onChange(RealmResults<ShopItem> shopItems) {
            shopItemList.addAll(shopItems);

            shopItemAdapter.notifyDataSetChanged();
        }
    });

Solution

  • It seems that onChange() is on the UI thread since when I commented the notifyDataSetChanged(), the adapter shows the list. I just made a new runnable inside the onChange() then it fixed that lag problem.

            @Override
            public void onChange(final RealmResults<ShopItem> shopItems) {
                Handler handler = new Handler();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        shopItemList.addAll(shopItems);
                        shopItemAdapter.notifyDataSetChanged();
                    }
                });
            }