我正在尝试将firebase应用到我的Android应用程序中,我希望能够按照它们显示的顺序将firebase中的所有条目拉入一个字符串数组中以放入ListView 这是原始的JSON:
[ 5, "quot", "waaaaa", "also a quote", "oh this one is a little longer man", "gosh really long. wow. im very inspired. golly gee wiz" ]
以及我用来尝试获取它的代码:
public class MyActivity extends ListActivity {
ArrayList<String> LIST = new ArrayList<String>();
Boolean wow = true;
Context context = this;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(context);
updateList();
}
public void makeList(ArrayList<String> input){
setListAdapter(new ArrayAdapter<String>(this, R.layout.mylist,input));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void updateList() {
Firebase myFirebaseRef = new Firebase("https://admin1.firebaseio.com/");
myFirebaseRef.child("0").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
int length = Integer.parseInt(snapshot.getValue().toString());
Firebase myFirebaseRef = new Firebase("https://admin1.firebaseio.com/");
for(int i=1; i<length; i++) {
String doIt = Integer.toString(i);
myFirebaseRef.child(doIt).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
LIST.add(snapshot.getValue().toString());
}
@Override
public void onCancelled(FirebaseError error) {
}
});
}makeList(LIST);
}
@Override
public void onCancelled(FirebaseError error) {
}
});
}
}
我原以为我可以将第一个(第0个)对象设置为条目数,然后使用.getValue循环遍历整个文件,但是当运行时我会出现内存异常并且应用程序强制关闭。我所确定的是相关的firebase内容是问题,而不是ListView。谢谢你的任何提示。
答案 0 :(得分:3)
首先,您的数据存储在JSON数据对象(即不是数组)中。 You do not want to store sequential, numeric ids in distributed data.
要收听第一个n
个对象,请使用the query methods和limitToFirst
。
int n = 10;
String URL = "https://<your instance>.firebaseio.com";
Firebase ref = new Firebase(URL);
Query queryRef = ref.orderByKey().limitToFirst(n);
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
Map<String, String> value = (Map<String, String)snapshot.getValue();
System.out.println(snapshot.getKey() + " was " + value.get("message"));
}
// ....
});