即时目标:从Firebase检索数据,以便我可以将其显示到Android中的日志信息
长期目标:从Firebase检索数据,以便我可以在TextView或其他视图中显示它
研究:Youtube,Google,Stackoverflow和Firebase文档(特别是https://firebase.google.com/docs/database/android/read-and-write)
我还尝试了什么:我已经尝试捕获错误或有条件,如果它只是发送一个日志,但实际上并没有修复错误,只是确保它不会崩溃。 / p>
错误:
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.netgalaxystudios.timeclock.RegisterSubscriptionActivity.onCreate(RegisterSubscriptionActivity.java:80)
此行发生错误: eNum = subscriptionInfo.get(0).toString();
我不确定我是否了解DataSnapshot ..具体说明.getValue方法
Firebase数据库: Firebase Database
RegisterSubscriptionActivity.java :
public class RegisterSubscriptionActivity extends Activity {
private DatabaseReference mDatabase;
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();
mDatabase.child("Subscription").addValueEventListener(new ValueEventListener() { //get everything UNDER subscription
@Override
public void onDataChange(DataSnapshot dataSnapshot) { //literally a "snapshot" of the data
for(DataSnapshot subscriptionDataSnapshot : dataSnapshot.getChildren()) {
String subscriptions = subscriptionDataSnapshot.getValue(String.class);
subscriptionInfo.add(subscriptions);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//MICRO
//mNum = subscriptionInfo.get(6).toString();
// mPrice = subscriptionInfo.get(7).toString();
// micro = subscriptionInfo.get(11).toString();
//ENTERPRISE
eNum = subscriptionInfo.get(0).toString();
Log.i("enterprise number", eNum);
请帮助我理解我缺少的东西或我需要进一步了解的地方,谢谢!
答案 0 :(得分:0)
从Firebase is asynchronous读取数据。
这意味着当您尝试访问第一个元素时,结果(可能)尚未存储在subscriptionInfo
中:
eNum = subscriptionInfo.get(0).toString();
尝试访问不存在的ArrayList的索引会导致您面临的IndexOutOfBoundsException
。
您可以将记录步骤移动到事件处理程序:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot subscriptionDataSnapshot : dataSnapshot.getChildren()) {
String subscriptions = subscriptionDataSnapshot.getValue(String.class);
subscriptionInfo.add(subscriptions);
}
}
eNum = subscriptionInfo.get(0).toString();
Log.i("enterprise number", eNum);
}