How to store data in realtime database properly under user authenticated key?

前端 未结 2 1326
粉色の甜心
粉色の甜心 2020-12-12 04:40

I have stored some data in realtime database under autenticated key using shared preferences. I used SharedPreferences because I used multiple pages for getting

相关标签:
2条回答
  • 2020-12-12 05:13

    Moved the answer to this post because second one was closed as a duplicate -

    In order to get what you're looking for you'll need to iterate on the list of details you have and set one at a time as a value under your user's UID OR just create an object with all of the params you need and send the object.

    Example with HashMap to iterate :

    HashMap hashMap = new HashMap();
    
    SharedPreferences sp = getSharedPreferences("Mypref", 0);
    hashMap.put("first_name", sp.getString("first_name", null))
    hashMap.put("last_name", sp.getString("last_name",null))
    hashMap.put("fathers_name", sp.getString("fathers_name", null))
    hashMap.put("date", sp.getString("date", null))
    hashMap.put("income", sp.getString("income", null))
    (.......)
    
    Iterator iterator = hashMap.entrySet().iterator() 
    if (hashMap.hasNext()) {
        iterator.next() 
        reference.child("User").child(Objects.requireNonNull(mAuth.getUid())).child(iterator.getKey).setValue(iterator.getValue);
    }
    
    0 讨论(0)
  • 2020-12-12 05:19

    You are getting that unwanted extra level (all) in the database because when you are write the data using:

    reference.child("User").child(Objects.requireNonNull(mAuth.getUid())).setValue(sp);
    

    You are passing to the setValue() method a SharedPreferences object:

    SharedPreferences sp = getSharedPreferences("Mypref", Context.MODE_PRIVATE);
    

    And not the data that is stored in that object. Inside your sp object, the data is stored as a Map containing key and value pairs. The first key in that object is all and the value is your actual data. That's the reason you have that structure. To solve this, simply get the data out from your sp object, save it into a Users object and write it to the database. In this way you'll have a database tree without that extra node.

    0 讨论(0)
提交回复
热议问题