ViewModel每次都被调用

时间:2017-12-26 10:57:16

标签: android firebase firebase-realtime-database android-architecture-components android-livedata

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

我的问题是,即使我锁定手机并将其解锁,也会再次调用所有内容,并在RecyclerView中复制数据。我无法理解问题是什么。请帮忙。

2 个答案:

答案 0 :(得分:1)

首先了解情景:

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

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

所以你的逻辑存在于onCreate()方法中,这就是为什么一次又一次地调用所有东西。

要解决此问题,您需要清除类别列表&#39;或者再次在同一个地方初始化它,以便创建它的新实例而不包含任何数据。

答案 1 :(得分:0)

在添加iteam之前清除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();
        }
    });