4 回答

TA贡献1816条经验 获得超6个赞
这里有一个疯狂的想法,在onDataChange里面,把它放在一个TextView中,可见性消失textview.setVisiblity(Gone)
了,然后做一些像
textview.setText(dataSnapshot.getValue(String.class))
然后再拿到它 textview.getText().toString()
只是一个疯狂的简单想法。

TA贡献1893条经验 获得超10个赞
我相信我明白你在问什么。虽然你说你想从fetch方法“返回”它(本身),但是你可能只想说你实际上只想在你的fetch完成后使用检索到的值。如果是这样,这就是你需要做的:
在类的顶部创建一个变量
检索您的值(您最常做的正确)
将类中的公共变量设置为等于检索的值
一旦你的获取成功,你可以用变量做很多事情。图4a和4b是一些简单的例子:
4A。编辑: 作为使用示例,您可以触发在您使用的类中运行所需的任何其他内容yourNameVariable
(并且您可以确定它yourNameVariable
不为null)
4B。编辑: 作为使用示例,您可以在由按钮的onClickListener触发的函数中使用该变量。
试试这个。
// 1. Create a variable at the top of your classprivate String yourNameVariable; // 2. Retrieve your value (which you have done mostly correctly)private void getUserName(String uid) { databaseReference.child(String.format("users/%s/name", uid)) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // 3. Set the public variable in your class equal to value retrieved yourNameVariable = dataSnapshot.getValue(String.class); // 4a. EDIT: now that your fetch succeeded, you can trigger whatever else you need to run in your class that uses `yourNameVariable`, and you can be sure `yourNameVariable` is not null. sayHiToMe(); } @Override public void onCancelled(DatabaseError databaseError) {} });}// (part of step 4a)public void sayHiToMe() { Log.d(TAG, "hi there, " + yourNameVariable);}// 4b. use the variable in a function triggered by the onClickListener of a button.public void helloButtonWasPressed() { if (yourNameVariable != null) { Log.d(TAG, "hi there, " + yourNameVariable); }}
然后,您可以yourNameVariable
在整个班级中随处使用。

TA贡献1830条经验 获得超9个赞
这是有效的,您可以通过将值作为参数传递给另一个函数来使用onDataChange外部的数据快照中的值,请在下面看到我的答案它正在工作,我在我的应用程序中使用它。
// Get Your Valueprivate void getValue() { fbDbRefRoot.child("fbValue").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String yourValue = (String) dataSnapshot.getValue(); useValue(yourValue); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } });}// Use Your Valueprivate void useValue(String yourValue) { Log.d(TAG, "countryNameCode: " + yourValue);}
我和Rbar的答案之间的主要区别在于我将值作为参数传递给函数然后使用它。
添加回答
举报