ViewModel 每次都被调用

ViewModel getting called everytime

我在 Firebase 中使用 LiveData 和 ViewModel。我正在使用以下代码在 RecyclerView 中显示数据。

public class CategoryActivity extends AppCompatActivity {

@BindView(R.id.toolbar_category)
Toolbar toolbar;
@BindView(R.id.recycler_view_category)
RecyclerView categoryRecyclerView;
private List<Category> categoryList = new ArrayList<>();
private CategoryAdapter mAdapter;
private Context context;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category);
    ButterKnife.bind(this);
    setSupportActionBar(toolbar);
    context = this;

    mAdapter = new CategoryAdapter(categoryList, context);
    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    categoryRecyclerView.setLayoutManager(mLayoutManager);
    categoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
    categoryRecyclerView.setAdapter(mAdapter);    
    CategoryViewModel categoryViewModel = ViewModelProviders.of(this).get(CategoryViewModel.class);
    LiveData<DataSnapshot> liveData = categoryViewModel.getDataSnapshotLiveData();
    liveData.observe(this, new Observer<DataSnapshot>() {
        @Override
        public void onChanged(@Nullable DataSnapshot dataSnapshot) {

            Log.e("CategoryActivity","inside");
            Iterable<DataSnapshot> dataSnapshotIterable = dataSnapshot.getChildren();
            for (DataSnapshot p : dataSnapshotIterable) {
                Category categoryFromFirebase = p.getValue(Category.class);
                categoryList.add(categoryFromFirebase);
            }
                mAdapter.notifyDataSetChanged();
        }
    });
}
}

我的问题是,即使我锁定 phone 并解锁它,所有内容都会再次调用并且数据会在 RecyclerView 中重复。我无法理解问题出在哪里。请帮忙

在添加项目之前清除您 arraylist categoryList.clear();

liveData.observe(this, new Observer<DataSnapshot>() {
        @Override
        public void onChanged(@Nullable DataSnapshot dataSnapshot) {

       categoryList.clear(); //clear your arraylist values before adding

            Log.e("CategoryActivity","inside");
            Iterable<DataSnapshot> dataSnapshotIterable = dataSnapshot.getChildren();
            for (DataSnapshot p : dataSnapshotIterable) {

                Category categoryFromFirebase = p.getValue(Category.class);

                categoryList.add(categoryFromFirebase);

            }

                mAdapter.notifyDataSetChanged();
        }
    });

首先了解场景:

设备锁定:将调用 onDestroy()、onCreate()、onStart()、onResume() 方法

设备解锁: onResume() 方法将调用

所以您的逻辑驻留在 onCreate() 方法中,这就是为什么所有内容都被一次又一次调用的原因。

要解决此问题,您需要清除 'categoryList' 或在同一位置再次对其进行初始化,以便创建其中没有任何数据的新实例。