gpt4 book ai didi

java - firebase 将数据作为数组获取

转载 作者:行者123 更新时间:2023-12-01 22:25:07 24 4
gpt4 key购买 nike

我正在尝试将 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。感谢您的任何提示。

最佳答案

首先,您的数据存储在 JSON 数据对象中(即不是数组)。 You do not want to store sequential, numeric ids in distributed data.

要监听前 n 个对象,请使用 the query methodslimitToFirst

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"));
}
// ....
});

关于java - firebase 将数据作为数组获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com