簡體   English   中英

變量僅存儲 Firebase 數據庫的最后一個值

[英]Variable is only storing last value of Firebase 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) {

        }
    });

要解決此問題,請使用以下代碼行:

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 ,你可以做任何你需要做的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM