目标:我正在尝试从Firebase提取数据并将值从嵌套节点插入字符串(在Android中)。
注意 :第一个变量/键值对(mNum)很精细但其他人获得NullPointer
研究:关于此特定问题的Firebase文档,Youtube,Stackoverflow,包括:How to get child of child value from firebase in android?
这如何适用于其他人:无法在DB具有多个嵌套时查找有关获取Firebase数据库信息的信息
错误:
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:211)
at com.netgalaxystudios.timeclock.RegisterSubscriptionActivity$1.onDataChange(RegisterSubscriptionActivity.java:80)
错误指向此行:Log.i(" micro name",micro);
RegisterSubscriptionActivity.java :
public class RegisterSubscriptionActivity extends Activity {
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseMicro;
ArrayList subscriptionInfo;
//Subscription (String) values
String micro, small, medium, large, enterprise;
String mNum, sNum, medNum, lNum, eNum;
String mPrice, sPrice, medPrice, lPrice, ePrice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_subscription);
subscriptionInfo = new ArrayList<>();
//GET INSTANCE OF FIREBASE DB & GRAB SUBSCRIPTION DATA
mDatabase = FirebaseDatabase.getInstance().getReference("Subscription");
mDatabaseMicro = mDatabase.child("Micro");
mDatabaseMicro.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) { //literally a "snapshot" of the data
//dataSnapshot.
for(DataSnapshot subscriptionDataSnapshot : dataSnapshot.getChildren()) {
if (subscriptionDataSnapshot.getKey().equals("mNum")) {
mNum= subscriptionDataSnapshot.getValue().toString();
}
if(subscriptionDataSnapshot.getKey().equals("mPrice")) {
mPrice = subscriptionDataSnapshot.getValue().toString();
}
if(subscriptionDataSnapshot.getKey().equals("micro")) {
micro = subscriptionDataSnapshot.getValue().toString();
}
Log.i("micro number", mNum);
//Log.i("micro price", mPrice);
Log.i("micro name", micro);
String subscriptions = subscriptionDataSnapshot.getValue(String.class); //Each time it gets the key/value pair per node
subscriptionInfo.add(subscriptions);
}
答案 0 :(得分:1)
要获取Micro
节点下的数据,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference microRef = rootRef.child("Subscription").child("Micro");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String mNum = ds.child("mNum").getValue(String.class);
String mPrice = ds.child("mPrice").getValue(String.class);
String micro = ds.child("micro").getValue(String.class);
Log.d("TAG", mNum + " / " + mPrice + " / " + micro);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
microRef.addListenerForSingleValueEvent(eventListener);
你的出局将是:
10 Employees / 25 / Micro
答案 1 :(得分:0)
您的意思是将这些日志语句放在for循环之外吗?第一次通过循环时它将匹配“mNum”,但micro
仍将为空。