Last Updated
Viewed 26 Times

I have a static array of dates - String[] dates = new String[MAX_DAYS].

Each date is in the format of yyyyMMdd and the array is sorted alphabetically

(e.g. dates[0] = "20200102", dates[1] = "20200101", dates[2] = "20191231", dates[3] = "20191230" and so on )

I also have a database (I use Firebase Database) that stores dates (in said format), like this :

{   
  "key" : {
    "aaa" : "20191230",
    "bbb" : "20191231",
    "ccc" : "20191231",
    "ddd" : "20191231",
    "eee" : "20200101",
    "fff" : "20200101",
    "ggg" : "20200103"
    }
}

I want to check for each value in the dates array (minus the first index) if that value appears at least once in the database. (i.e. if all values, but first, of dates exist in database do something, otherwise do something else)

I created a query that fetches only the children under key whose value is between dates[1] and dates[dates.length - 1]:

// reference to "key" node
ref.orderByValue().startAt(dates[dates.length - 1]).endAt(dates[1])
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for(DataSnapshot ds : dataSnapshot.getChildren()) {

                        }
                    }

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

What would be the most efficient way of finding out if all values of dates exist in the database? Do I simply store each child's value in another array and then loop both arrays? Or is there a better way?

I'm making an edit page for the user profile in Firebase. I've tried a few different ways. But I could not update. Just a added as a new user to the database.

I am getting new values in the Alert Dialog. Please help me.

My Update Method Code's :

public void editAlert() {
        LayoutInflater layoutInflater = LayoutInflater.from(ProfilePage.this);

        View design = layoutInflater.inflate(R.layout.edit_profile, null);

        final EditText editTextUserName = design.findViewById(R.id.username_editTextProfileEdit);

        final EditText editTextRealName = design.findViewById(R.id.realName_editTextProfileEdit);

        final EditText editTextSurname = design.findViewById(R.id.username_editTextProfileEdit);

        final EditText editTextEmail = design.findViewById(R.id.email_editTextProfileEdit);

        final EditText editTextPassword = design.findViewById(R.id.password_editTextProfileEdit);


        AlertDialog.Builder alertDialoga = new AlertDialog.Builder(ProfilePage.this);
        alertDialoga.setTitle("Edit Profile");
        alertDialoga.setView(design);
        alertDialoga.setPositiveButton("Finish", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String username = editTextUserName.getText().toString().trim();
                String realName = editTextRealName.getText().toString().trim();
                String surname = editTextSurname.getText().toString().trim();
                String email = editTextEmail.getText().toString().trim();
                String password = editTextPassword.getText().toString().trim();
                String admin = "false";
                String url = "test_url";


                String key = myRef.push().getKey();

                Users user = new Users(key,username,realName,surname,email,password,url,admin);


                HashMap<String,Object> data = new HashMap<>();

                data.put("user_email", email);
                data.put("user_name", realName);
                data.put("user_password", password);
                data.put("user_surname", surname);
                data.put("username", username);

                myRef.child(user.getUser_id()).updateChildren(data);

                Toast.makeText(ProfilePage.this, "Uptaded!", Toast.LENGTH_SHORT).show();
            }
        });

        alertDialoga.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        alertDialoga.show();
    }

My Create User Code's :

  // Sign Up Method
    // Kullanıcı Kayıt etme metodu
    public void signUp(View view) {
        UUID uuid = UUID.randomUUID();
        final String imageName = "ProfileImages/"+uuid+".jpg";
        final ProgressDialog dialog = new ProgressDialog(signupPage.this);
        dialog.setTitle("Creating user record.. ");
        dialog.setMessage("User registration is in progress..");
        dialog.show();
        StorageReference storageReference = mStorageRef.child(imageName);
        storageReference.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // Url

                StorageReference newReference = FirebaseStorage.getInstance().getReference(imageName);
                newReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {

                        dowloadURL = uri.toString();

                        if (dowloadURL != null) {
                            mAuth.createUserWithEmailAndPassword(emailText.getText().toString(), passwordText.getText().toString())
                                    .addOnCompleteListener(signupPage.this, new OnCompleteListener<AuthResult>() {
                                        @Override
                                        public void onComplete(@NonNull Task<AuthResult> task) {
                                            if (task.isSuccessful()) /* Kullanıcı girişi başarılı ise bu çalışacak */ {
                                                Toast.makeText(signupPage.this, "User Created", Toast.LENGTH_SHORT).show();
                                                String userName = user_name.getText().toString();
                                                String userSurname = user_surname.getText().toString();
                                                String username = user_username.getText().toString();
                                                String user_email = emailText.getText().toString();
                                                String key = myRef.push().getKey();
                                                String password = user_password.getText().toString();
                                                String imageURL = dowloadURL;

                                                Users user = new Users(key, userName, username, userSurname, user_email, password,imageURL, admin);
                                                myRef.push().setValue(user);
                                                Intent homePage = new Intent(signupPage.this, ProfilePage.class);
                                                startActivity(homePage);
                                                finish();
                                                dialog.dismiss();

                                            } else /* Kullanıcı girişi başarısız ise bu çalışacak */ {
                                               /*Intent signBack = new Intent(signupPage.this, signupPage.class);
                                                startActivity(signBack);
                                                finish(); */
                                                dialog.dismiss();
                                            }



                                        }
                                    }).addOnFailureListener(signupPage.this, new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }


                    }
                });


            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });


    }

The download url comes from a separate image selection method, by the way. My user creation codes are like this.

I have read the question on how get value with it's child in Firebase.

enter image description here

Now I want to convert that value into a Java object. Can I do that? If can, how I can achieve that?

So I have been trying to download data from Firebase into an ArrayList:

 public void updateOnce(){
    animalList = new ArrayList<>();
    Query query = mDatabase.orderByChild("id");
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
                    SpottedAnimal pet = messageSnapshot.getValue(SpottedAnimal.class);
                    animalList.add(pet);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Debugger shows that the Object SpottedAnimal pet does get created and then inserted into the animalList that is a global ArrayList. But once I call the method:

public ArrayList<SpottedAnimal> getList(){
    return animalList;
}

The animalList comes out empty on the other side.

 FirebaseGetList() animalListHook = new FirebaseGetList(); 
 animalListHook.updateOnce();
 ArrayList<SpottedAnimal> animalList = animalListHook.getList();

Similar Question 5 (1 solutions) : Firebase Android Java - Can't get value of a child

Similar Question 7 (1 solutions) : Java Android Retrieve Pushed Key Data from Firebase

cc