【问题标题】:Accessing a Firebase variable from another class [duplicate]从另一个类访问 Firebase 变量 [重复]
【发布时间】:2018-03-14 00:01:44
【问题描述】:

我撞到了一堵墙,找不到绕过它的路。我有以下课程,我从 fetchToDo() 方法中的 Firestore 数据库获取信息。

public class FetchToDo {
private static final String LOG_TAG = FetchToDo.class.getName();

public static final String AUTHOR_KEY = "author";
public static final String EMAIL_KEY = "e-mail";

/**
 * Access cloud Firestore instance
 */
FirebaseFirestore db = FirebaseFirestore.getInstance();

private String mTitle;
private String mDescription;

private DocumentReference mDocRef;

public void fetchToDo() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    final String emailOfUser = user.getEmail();

    mDocRef = FirebaseFirestore.getInstance().document("users/" + emailOfUser);

    mDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            if (documentSnapshot.exists()) {
                Log.i(LOG_TAG, "Method ran");
                mTitle = documentSnapshot.getString(EMAIL_KEY);
                mDescription = documentSnapshot.getString(AUTHOR_KEY);

            }
        }
    });
}

public String getTitle(){
    fetchToDo();
    return this.mTitle;
}

获得这些信息后,我想将其存储到 RecyclerView 中并显示出来。我在创建 RecyclerView 时执行以下操作。

public void createRecyclerView(){
    //Get a reference of the RecyclerView
    mToDoList = (RecyclerView) findViewById(R.id.rv_to_do);

    //Assign a Layout manager - this case a linear one
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    mToDoList.setLayoutManager(layoutManager);

    mToDoList.setHasFixedSize(true);

    //Create a new ToDoAdapter

    FetchToDo fetchToDo = new FetchToDo();
    String title = fetchToDo.getTitle();
    String[] fua = {"Test1", title};
    mAdapter = new ToDoAdapter(fua);
    mToDoList.setAdapter(mAdapter);
}

问题在于 RecyclerView 显示了两个框,一个带有“Test1”字符串,另一个是空的。

谢谢。

【问题讨论】:

  • 将日志行放入代码中以查看调用的顺序。您会发现 Firebase API 是异步的,您需要以这种方式处理它们。 medium.com/google-developers/…

标签: java android firebase google-cloud-firestore


【解决方案1】:

您必须将FetchToDo() 视为异步函数。而您正在做的是在实际获取“标题”之前询问它。

我的建议是在FetchToDo() 函数或任何类型的完成监听器中返回它。或者,您可以将 mTitle 变量设为静态并创建一个简单的 observable,以便在标题更新时加载 RecyclerView。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多