Jane
Jane

Reputation: 71

How to use HashMap to get the data from child of child in Firebase in android?

I'm beginner for the Firebase. Could I know how do I retrieve data from child to child from firebase by using HashMap? Could I know how to store ArrayList into HashMap? If I don't use ArrayList, could HashMap replace the ArrayList?

I want to do the function which let the user be able to add the car plate into the firebase-database. I will be using the ArrayList to let the user to add a list of car plate into the system. The code will be shown like that

List<String>carPlate=new ArrayList<String>();

 mDatabase = FirebaseDatabase.getInstance().getReference();
    user = FirebaseAuth.getInstance().getCurrentUser();
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            phone = Phone.getText().toString();
            ic = IC.getText().toString();
            fullname = FullName.getText().toString();
            carplate = CarPlate.getText().toString();
            carPlate.add(carplate);

           //this data will be successful storing in firebase-database and the results will be the images above
            Account account = new Account(fullname, phone, carPlate, ic);
            if(user!=null) {
                mDatabase.child(user.getUid()).setValue(account);
                Toast.makeText(getBaseContext(), "Register Successfully...", Toast.LENGTH_LONG).show();
                Intent in = new Intent(RegisterPage.this, MainActivity.class);
                startActivity(in);
                finish();
            }

        }
    });
}

Besides, another class which contain the update function as shown at below: //THE PROBLEM IS AT HERE
Now I want to update the data. According to this Firebase-database, I try to map.get all the value and then using setter for encapsulation. After that, I remove the data from firebase-database. Then I create new object and then put all the task inside. Finally, I setvalue to firebase-database. After I update the new data, the firebase-database will be automatically push to second level.

First Results

When I update again, it will push it again

Second Results

The second problem is NullException at this line: phoneAcc.set_IC(map.get("_IC"));

The error

E/UncaughtException: java.lang.NullPointerException
                     at com.google.online_mobile_flexi_parking.ChangeEmailPassword$8$1.onDataChange(ChangeEmailPassword.java:251)
                     at com.google.android.gms.internal.zzakg.zza(Unknown Source)
                     at com.google.android.gms.internal.zzalg.zzcxk(Unknown Source)
                     at com.google.android.gms.internal.zzalj$1.run(Unknown Source)
                     at android.os.Handler.handleCallback(Handler.java:733)
                     at android.os.Handler.dispatchMessage(Handler.java:95)
                     at android.os.Looper.loop(Looper.java:136)
                     at android.app.ActivityThread.main(ActivityThread.java:5028)
                     at java.lang.reflect.Method.invokeNative(Native Method)
                     at java.lang.reflect.Method.invoke(Method.java:515)
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
                     at dalvik.system.NativeStart.main(Native Method)

and here is my code:

private List CarPlate;
         changePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);
                txtPhone = newPhone.getText().toString().trim();
                if (!txtPhone.equals("")) {
                    mDatabase.child(user.getUid()).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            String key=mDatabase.child(user.getUid()).getKey();
                            Account phoneAcc=new Account();
                            Map<String,String>map=(Map)dataSnapshot.getValue();
                            phoneAcc.set_Key(mDatabase.child(user.getUid()).getKey());
                            phoneAcc.set_IC(map.get("_IC"));
                            phoneAcc.set_Phone(txtPhone);
                            phoneAcc.set_FullName(map.get("_FullName"));
                            CarPlate.add(map.get("_CarPlate0"));
                            phoneAcc.set_CarPlate0(CarPlate);

                            //dataSnapshot.getRef().removeValue();

                            mDatabase.child(mDatabase.child(user.getUid()).getKey()).removeValue();
                            Map<String,Object> task=new HashMap<String,Object>();
                            task.put("_FullName",phoneAcc.get_FullName());
                            task.put("_CarPlate0",phoneAcc.get_CarPlate0());
                            task.put("_Phone",phoneAcc.get_Phone());
                            task.put("_IC",phoneAcc.get_IC());
                            mDatabase.child(phoneAcc.get_Key()).setValue(task);
     Toast.makeText(ChangeEmailPassword.this, "Phone Number is updated, sign in with new password!", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
                                finish();
                                signOut();
      progressBar.setVisibility(View.GONE);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });


                    } else if (txtPhone.equals("")) {
                        newPhone.setError("Enter phone number");
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });

Upvotes: 2

Views: 7891

Answers (1)

Rahul
Rahul

Reputation: 10625

Create a method to pull data and pass tag from outside, but must note that tag should be on root node.

public void fetchData(@NonNull String tag) {
    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
            .child(tag);
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
               String value = dataSnapshot.getValue(String.class);
               Log.d("Value is", value);
         }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

Call this method from your activity like this -

fetchData("_CarPlate");

Upvotes: 2

Related Questions