每秒更新数据Firebase Android

时间:2019-07-02 12:19:45

标签: android firebase

我正在从Firebase中提取数据。例如,我正在执行开-关部分,在数据库中的时钟更新时进行开-关。但是当我进出应用程序时,该数据将更新。我希望在不离开应用程序的情况下更新这些数据。例如,我要连续更新time_textview中的数据。因此,我想使用timer每秒钟从Firebase中提取数据。我希望更新time_textview中的数据。我该怎么办?

主班

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnItemSelectedListener, View.OnTouchListener, RadioGroup.OnCheckedChangeListener{
    ProductsAdapter adapter;
    List<Product> productList;
    dbProducts.addListenerForSingleValueEvent(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
           productList = new ArrayList<>();
           if (dataSnapshot.exists()) {
               for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
                   Product p = productSnapshot.getValue(Product.class);
                   productList.add(p);
               }

               adapter = new ProductsAdapter(MainActivity.this, productList);
                                        recyclerView.setAdapter(adapter);

           }
       }

       @Override
       public void onCancelled(DatabaseError databaseError) {

       }


  });
  }

主适配器:

 public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductViewHolder> {
        List<Product> productList;

            public void onBindViewHolder(final ProductViewHolder holder, final int position) {
                Product product = productList.get(position);
                holder.textViewTime.setText(product.gettime());
    }

        class ProductViewHolder extends RecyclerView.ViewHolder {
            TextView textViewTime, textTitle, textviewPlaces;
                textViewTime = itemView.findViewById(R.id.time_textView);
    }
  }

1 个答案:

答案 0 :(得分:0)

使用ValueEventListener代替使用SingleValueEventListener喜欢

   public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnItemSelectedListener, View.OnTouchListener, RadioGroup.OnCheckedChangeListener{
ProductsAdapter adapter;
List<Product> productList = new ArrayList<>();
adapter = new ProductsAdapter(MainActivity.this, productList);
recyclerView.setAdapter(adapter);


dbProducts.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       productList.clear();
       if (dataSnapshot.exists()) {
           for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
               Product p = productSnapshot.getValue(Product.class);
               productList.add(p);
           }

    // here I will recommend just to notify adapter, and initialize it once outside the listener
           adapter.notifyDataSetChanged();

       }
   }

   @Override
   public void onCancelled(DatabaseError databaseError) {

   }


 });
}

现在,每次在数据库中更改数据时,该监听器都会自动被调用,您将获取最新数据。然后,您只需清除较旧的列表,在其中插入新的数据,然后调用adapter.notifyDataSetChanged()