我正在尝试从Firebase获取多个嵌套数据,但出现此hashmap错误

时间:2019-06-10 18:15:14

标签: android firebase firebase-realtime-database

   ListView listView;
   FirebaseDatabase firebaseDatabase;
   DatabaseReference databaseReference;
   ArrayList<String> arrayList = new ArrayList<>();
   ArrayAdapter<String> arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firebaseDatabase = FirebaseDatabase.getInstance();
    databaseReference = firebaseDatabase.getReference("Users");


    listView = (ListView) findViewById(R.id.listview);

       Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
        databaseReference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Log.i( "he","Reference : " + databaseReference.toString() );
            String value = dataSnapshot.getValue(String.class);
            arrayList.add(value);
            arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
            listView.setAdapter(arrayAdapter);

        }

这是我遇到的错误:

  

com.google.firebase.database.DatabaseException:转换失败   类型java.util.HashMap的值转换为String           在com.google.android.gms.internal.firebase_database.zzkt.zzb(未知   资源)           位于com.google.android.gms.internal.firebase_database.zzkt.zza(未知   资源)           位于com.google.firebase.database.DataSnapshot.getValue(未知来源)           在com.example.test.MainActivity $ 1.onChildAdded(MainActivity.java:86)           在com.google.android.gms.internal.firebase_database.zzbt.zza(未知   资源)           在com.google.android.gms.internal.firebase_database.zzgx.zzdr(未知   资源)           在com.google.android.gms.internal.firebase_database.zzhd.run(未知   资源)           在android.os.Handler.handleCallback(Handler.java:751)           在android.os.Handler.dispatchMessage(Handler.java:95)           在android.os.Looper.loop(Looper.java:154)           在android.app.ActivityThread.main(ActivityThread.java:6119)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

1 个答案:

答案 0 :(得分:0)

在这一行

String value = dataSnapshot.getValue(String.class);

您正在尝试获取价值。尝试在=的左侧如此使字符串值为左侧,这也假定是字符串。为了在getValue中做到这一点,您需要使用pojo类。而且只有在提取价值之后。例如

User user = dataSnapshot.getValue(User.class);
String finalValue = user.getSomeString();