gummybear
gummybear

Reputation: 35

How to check if the data in my child exists?

This is the code, and it doesn't check if the value in my editText exists.

mSubmitBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        final String title_val = mPostTitle.getText().toString().trim();
        mDatabase2 = FirebaseDatabase.getInstance().getReference().child("Forums");
        mDatabase2.child("title").child("KS1: "+title_val).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()) {
                    String success = "Your title already exists...";
                    Toast.makeText(PostActivityKinderSection1.this, success, Toast.LENGTH_LONG).show();
                    mSubmitBtn.setEnabled(true);
                }
                else {
                    mSubmitBtn.setEnabled(false);
                    startPosting();
                }
            }
        });
    }
});

I want to avoid saving multiple times with the same title in my firebase.

enter image description here

Upvotes: 2

Views: 130

Answers (1)

Gaëtan Maisse
Gaëtan Maisse

Reputation: 12347

You can not only check if title child exist, you have to iterate over all forums to find out if there is already one with title you want to save. You can do it like this:

final String title_val = "KS1: " + mPostTitle.getText().toString().trim();
mDatabase2 = FirebaseDatabase.getInstance().getReference().child("Forums");
mDatabase2.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    void onDataChange(DataSnapshot forumsSnapshot) {
        boolean isTitleAlreadyUsed = false;

        for (DataSnapshot specificForum : forumsSnapshot.getChildren()) { 
            // Check if key 'title' exists and if title value is equal to value to save (title_val)  
            if (specificForum.hasChild("title") && (title_val.equals(specificForum.child("title").getValue()))){
                isTitleAlreadyUsed = true;
            }
        }

        if (isTitleAlreadyUsed) {
            String success = "Your title already exists...";
            Toast.makeText(PostActivityKinderSection1.this, success, Toast.LENGTH_LONG).show();
            mSubmitBtn.setEnabled(true);
        }
        else {
           mSubmitBtn.setEnabled(false);
           startPosting();
        }
    }
}   

If you have performance issue try to replace for-loop with while-loop, or use the title as child key in your db construction.

Upvotes: 2

Related Questions