变量仅存储Firebase数据库的最后一个值

时间:2019-01-10 16:35:09

标签: java android firebase firebase-realtime-database

我正在从Firebase实时数据库中检索所有电话号码,并且在dataSnapshot中检索了所有电话号码,但是在将phoneNumber存储在String obj中时,仅显示最后一个值。请问如何保存所有值?谢谢。

代码

databasePhone.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot readphone : dataSnapshot.getChildren()) {
                Log.v("tmz",""+ readphone.getKey()); //displays the key for the node
                obj = readphone.child("phoneNumber").getValue().toString();
                try {
                    FileOutputStream fileOutputStream = openFileOutput(file_name,MODE_PRIVATE);
                    fileOutputStream.write(obj.getBytes());
                    fileOutputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

1 个答案:

答案 0 :(得分:0)

要解决此问题,请使用以下代码行:

ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> phoneNumberList = new ArrayList<>();
        FileWriter writer = new FileWriter("output.txt");
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String phoneNumber = ds.child("phoneNumber").getValue(String.class);
            phoneNumberList.add(phoneNumber);
            writer.write(phoneNumber);
        }
        //Do what you need to do with your list
        Log.d(TAG, phoneNumberList.toString());
        writer.close();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
databasePhone.addListenerForSingleValueEvent(valueEventListener);

看,我把所有电话号码都当作字符串,并将它们添加到列表中。现在有了phoneNumberList,您可以做任何需要做的事情。