从Firebase(android)获取数据时,如何避免代码重复? [英] How can I avoid code duplication when getting data from Firebase (android)?

查看:62
本文介绍了从Firebase(android)获取数据时,如何避免代码重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这个问题将适用于所有使用异步调用的应用程序.

I'd imagine this question would apply to any application that uses asynchronous calls.

我在这方面还比较陌生,而我遇到的问题是从Firebase到我的Android应用程序中获取数据.

I'm relatively new to all this, and the problem I'm having is with with fetching data from Firebase to my Android application.

整个应用程序中有几个类需要使用数据库中用户"表中的数据,我可以通过以下方式获得这些数据:

There are several classes throughout the application that need to use data from the "users" table in the database, which I obtain as follows:

DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("users").child("exampleDataFromUsers");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // do something with the snapshot
    }

我想创建一个通用类来处理从Firebase检索的数据,例如:

I'd like to create a general purpose class for handling data retrieval from Firebase, something like:

public class FirebaseDataHandler() {

  static String getUserReports() {
    // get Reports
  }

  static int getUserAge() {
    // get age
  }
}

,但是由于它是异步检索的,因此对这些方法的任何调用都只是返回null.结果,我的代码当前到处都是重复的代码.

but since it's being retrieved asynchronously, any calls to these methods simply return null. As a result, my code is currently littered with duplicate code.

如果有人对实现此目标的更好方法有任何见识,将不胜感激.谢谢.

If anyone has any insight into a better way to achieve this, it would be much appreciated. Thanks.

推荐答案

我相信这个问题将主要基于观点而产生许多好的答案.但是无论如何,我仍然会发表我的意见:

I believe this question will generate many good answers primarily based on opinions. But I will still post my opinion anyway:

我个人将Firebase与 Android体系结构组件一起使用该文档)是:

I personally use Firebase with Android Architecture Components, which (from the documentation) is:

可帮助您设计健壮,可测试的库的集合 可维护的应用程序.从用于管理UI组件的类开始 生命周期和处理数据持久性.

A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

该库提供了2个类,可让您了解数据生命周期:实时数据 ViewModel .您可以在Firebase博客上找到整合这两个库的指南: [Part1 Part2 第3部分] .

This libraries offers 2 classes to make your data lifecycle aware: Live Data and ViewModel. You can find a guide to integrate these 2 libraries on the Firebase Blog: [Part1, Part2, Part3].

要使用该库,您需要将Google存储库添加到项目的build.gradle文件中:

To use the library, you need to add the Google repository to your project's build.gradle file:

allprojects {
    repositories {
        jcenter()
        google()
    }
}

,然后在应用程序的build.gradle文件上添加依赖项:

and then add the dependency on your app's build.gradle file:

implementation "android.arch.lifecycle:extensions:1.1.0"

因此,您创建了一个从LiveData扩展的类:

So you create a class that extends from LiveData:

public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {
    private static final String LOG_TAG = "FirebaseQueryLiveData";

    private final Query query;
    private final MyValueEventListener listener = new MyValueEventListener();

    public FirebaseQueryLiveData(Query query) {
        this.query = query;
    }

    public FirebaseQueryLiveData(DatabaseReference ref) {
        this.query = ref;
    }

    @Override
    protected void onActive() {
        Log.d(LOG_TAG, "onActive");
        query.addValueEventListener(listener);
    }

    @Override
    protected void onInactive() {
        Log.d(LOG_TAG, "onInactive");
        query.removeEventListener(listener);
    }

    private class MyValueEventListener implements ValueEventListener {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            setValue(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e(LOG_TAG, "Can't listen to query " + query, databaseError.toException());
        }
    }
}

并创建一个ViewModel来加载该用户的数据:

And create a ViewModel which will load this user's data:

public class UserViewModel extends ViewModel{
  private static final DatabaseReference USERS_REF =
      FirebaseDatabase.getInstance().getReference("users/exampleDataFromUsers");

  private final FirebaseQueryLiveData liveData = new FirebaseQueryLiveData(USERS_REF);

  private final LiveData<String> liveData =
    Transformations.map(liveData, new Function<DataSnapshot, String> {
      @Override
      public String apply(DataSnapshot dataSnapshot) {
          //do something with the snapshot and return a String
      }
    });

  @NonNull
  public LiveData<String> getUserReports() {
      return liveData;
  }
}

最后,为了在活动中获取此数据,您只需要调用ViewModel并观察它的LiveData:

Finally, in order to get this data in your activities, you just need to call your ViewModel and observe it's LiveData:

    UserViewModel viewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    viewModel.getUserReports().observe(this, new Observer<String>() {
                @Override
                public void onChanged(@Nullable String reports) {
                    if (reports != null) {
                        // update the UI here with values
                    }
                }
            });

这篇关于从Firebase(android)获取数据时,如何避免代码重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆