Retrieving data from firebase

前端 未结 1 531
醉梦人生
醉梦人生 2020-12-12 00:02

I keep getting the stacktrace error below each time I implement

GenericTypeIndicator> t = new GenericTypeIndicator

        
相关标签:
1条回答
  • 2020-12-12 00:47

    Looking at your data structure:

    "Driver name" : {
      "-Js6OJniEqVZAYSNhqbB" : "gvvb",
      "-Js7GjPMGNOLurrKk9rC" : "iggvv",
      "-Js7GlUlCwIoljJxpFbZ" : "iiggv",
      "-Js7GnBCRogiFUfn-ncZ" : "ihccvv",
      "-Js7GqGxH2vLYK5tsjjP" : "hhvv",
      "-Js7Gs80AoB5eeWci6jW" : "hhgc",
      "-Js7Gtm6AGh_QaTUK6fQ" : "ugghh",
      "-Js7GyomOIzjtVo3-PVg" : "tyygff",
      "-JsPxEhf4tx7O4v7JWMc" : "",
      "-JsQBoMqVBF4SzOHF3WA" : "rr",
      "-JsQC6TuGqHrBBkdalik" : "eed"
    }
    

    You try to deserialize this into a List<String>. But it actually is a Map<String,String>. So:

    @Override
    public void onDataChange(DataSnapshot snapshot) {
        GenericTypeIndicator<Map<String,String>> mapType = new GenericTypeIndicator<Map<String, String>>() { };
        Map<String,String>  namelist =  snapshot.child("Driver name").getValue(mapType);
        Map<String,String> carlist =  snapshot.child("Drivers car").getValue(mapType);
        if (namelist!=null & carlist!=null) {
            for (String name: namelist.values()) {
                System.out.println(name);
            }
        }
    }
    

    Note that I have no idea how you're trying to match up a driver and their car. I highly recommend that you reconsider this data structure before you continue to code.

    One possible structure:

    "DriversList": {
      "-Js6OJniEqVZAYSNhqbB" : {
        "name": "puf",
        "available": false,
        "car": "Toyota RAV4"
      },
      "-Js7GjPMGNOLurrKk9rC" : {
        "name": "manon",
        "available": false,
        "car": "Toyota Matrix"
      },
      ...
    }
    

    To read/write these, you'll need a Driver class:

    public class Driver {
      String name;
      Boolean available;
      String car;
    
      public Driver() {}
    
      public String getName() { return name; }
      public Boolean getAvailable() { return available; }
      public String getCar() { return car; }
    }
    

    And then:

    public void onDataChange(DataSnapshot snapshot) {
        GenericTypeIndicator<Map<String,Driver>> mapType = new GenericTypeIndicator<Map<String, Driver>>() { };
        Map<String,Driver> drivers = snapshot.getValue(mapType);
        if (drivers!=null) {
            for (Driver driver: drivers.values()) {
                System.out.println(driver.name);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题