1

I have stored some data in realtime database under autenticated key using shared preferences. I used SharedPreferences because I used multiple pages for getting user data. While storing the data it is getting an extra node i.e. "all" node and I have not added this node anywhere in my code. The node should be in flow like (1) User->authkey->age and not like (2) User->authkey->all->age. Because of this extra node I am not able to retrive the data firebase. What should I do to make it like (1).

The below are the snippet of the database.

These are the number of users

This is the data under all node

Below is my code to store the data into my database

public class LoginDetails extends AppCompatActivity {
    EditText etemail_id,etpassword;
    TextView tvlogin_details;
    Button btregister,btback;
    FirebaseAuth mAuth;
    FirebaseDatabase database;
    DatabaseReference reference;
    Users users;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_details);
        etemail_id = (EditText) findViewById(R.id.etEmailid);
        etpassword = (EditText) findViewById(R.id.etPassword);

        tvlogin_details = (TextView) findViewById(R.id.tvLoginDetails);
        btback = (Button) findViewById(R.id.btBack);
        mAuth = FirebaseAuth.getInstance();
        btregister = (Button) findViewById(R.id.btRegister);
        database=FirebaseDatabase.getInstance();
        reference=database.getReference();
        users=new Users();
        btregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String email = etemail_id.getText().toString().trim();
                final String password = etpassword.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    etemail_id.setError("Provide your Email first!");
                    etemail_id.requestFocus();
                }
                else if (TextUtils.isEmpty(password)) {
                    etpassword.setError("Enter Password!");
                    etpassword.requestFocus();
                }
                else if (!(email.isEmpty() && password.isEmpty())) {
                    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(LoginDetails.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {

                                reference.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                        SharedPreferences sp = getSharedPreferences("Mypref", Context.MODE_PRIVATE);
                                        reference.child("User").child(Objects.requireNonNull(mAuth.getUid())).setValue(sp);
                                        Toast.makeText(getApplicationContext(), "data entered", Toast.LENGTH_SHORT).show();
                                    }
                                    @Override
                                    public void onCancelled(@NonNull DatabaseError databaseError) {

                                        Toast.makeText(getApplicationContext(), "database error", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                Toast.makeText(LoginDetails.this, "Successfully registered", LENGTH_LONG).show();
                                Intent it = new Intent(getApplicationContext(), Login.class);
                                startActivity(it);
                            }

                            else {
                                Toast.makeText(LoginDetails.this, "Registration Error", LENGTH_LONG).show();
                            }
                        }
                    });
                }
                else {
                    Toast.makeText(LoginDetails.this, "Error", Toast.LENGTH_SHORT).show();
                }
             }
        });

        btback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it1 = new Intent(getApplicationContext(), Preferences.class);
                startActivity(it1);
            }
        });
    }

}

`

Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46

2 Answers2

1

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • But I have multiple pages to store data that's why I have used shared preferences – Reetu Jaiswal Oct 24 '19 at 10:17
  • There is nothing wrong in storing the data in `SharedPreferences` and then share it across multiple activities but when you write it to the database, make sure the get the data out first. – Alex Mamo Oct 24 '19 at 10:34
  • Sorry Sir I am having problem in getting sp object data out and storing that data in Users. Can you please help me with that. – Reetu Jaiswal Oct 24 '19 at 10:56
  • Check [this](https://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) out. In your case you should use `getString()` method for each property and then pass all those values to the `Users` constructor or save each property separately. – Alex Mamo Oct 24 '19 at 11:01
  • I was trying to store the values of sp (object) in users(object) but not able to do that. – Reetu Jaiswal Oct 25 '19 at 09:52
  • Thats sounds basically as another question. In order to follow the rules of this community, please post another fresh question using its own [MCVE](https://stackoverflow.com/help/mcve), so me and other Firebase developers can help you. – Alex Mamo Oct 25 '19 at 10:00
0

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);
}
Itay Feldman
  • 846
  • 10
  • 23