firebase dataSnapshot.getValue(String.class)返回null

时间:2017-11-17 20:44:00

标签: android firebase firebase-realtime-database

Trying to get "Dio" from char_data

private View.OnClickListener saveBtnList;
    {
        saveBtnList = new View.OnClickListener() {
            public void onClick(View v) {
                characterName = (EditText)findViewById(R.id.charNameXML);
                str = characterName.getText().toString();

                DatabaseReference ref = charNameDatabaseReference.child("User/char_data");

                if(str.length() > 0) {
                    final CharacterInfoAdapter CIAdapter = new CharacterInfoAdapter(str);
                    charNameDatabaseReference.child("User/char_data").setValue(CIAdapter);

                    ref.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            String value = dataSnapshot.child("User/char_data").getValue(String.class);
                            System.out.println("You ight... Character Name is: " + value);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            System.out.println("You Thought :3");
                        }
                    });

                }
                saved = true;
                intent = new Intent(basic_info.this, character_select.class);
            }
        };
    }

我遇到的问题是我可以更新数据库,但无法提取信息,因为它始终返回null。如果我使用String value = dataSnapshot.getValue(String.class),我得到一个无法将Hash转换为String错误。

1 个答案:

答案 0 :(得分:0)

public void onDataChange(DataSnapshot dataSnapshot) {
    String value = null;
    for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
        value = postSnapshot.getValue(String.class);
    }
    System.out.println("You ight... Character Name is: " + value);
}

----而不是------

public void onDataChange(DataSnapshot dataSnapshot) {
                        String value = dataSnapshot.child("User/char_data").getValue(String.class);
                        System.out.println("You ight... Character Name is: " + value);
                    }