0

I am creating an object. Some of the variables are created within the app but some of variables are created after the query in Firebase. I have to obtain some information from database.

The problem is that I want to create this "ready to use" object with all variables assigned to it but I do not know how to do this.

This is my object:

public class Translations {

    private String nativeWord,foreignWord;
    private String description,useCases;
    private String examples;
    private Query query;

    public Translations(String mNativeWord,String mForeignWord){
        nativeWord = mNativeWord;
        foreignWord = mForeignWord;
    }

I want to have description,useCases and examples downloaded from database. I have created the method (in my Translations.class) like this:

 public void query(String queryWord){
        query = FirebaseDatabase.getInstance().getReference().orderByKey().equalTo(queryWord);

        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()) {
                    for (DataSnapshot ds : dataSnapshot.getChildren()) {

                        Translations a = ds.getValue(Translations.class);
                        nativeWord = a.getNativeWord();
                        description = a.getDescription();
                        useCases = a.getUseCases();
                        examples = a.getExamples();
                    }
                }


            }

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

            }
        });

    }

Now I walkaroud the problem by invoking the query method in my Activity class.

(I am getting object a from a ListView where I already have the foreignWord and nativeWord)

Translations a = (Translations) translationsListView.getItemAtPosition(i);
                a.query(a.getForeignWord());

                    foreignWord.setText(a.getForeignWord());
                    nativeWord.setText(a.getNativeWord());
                    description.setText(a.getDescription());
                    useCases.setText(a.getUseCases());
                    examples.setText(a.getExamples());

When I invoke query method right after the Translations object was created, the description, useCases and examples are null because the query is not finished yet. Later it is and it works fine.

I want to wait until the Translations object is completed with query finished and "ready to use" without any null variables. Then I want to set some texts. How to do it?

NOTE: I am aware that invoking query method on the Activity isn't the best idea. It should be inside Translations.class but I do not know how to write it properly.

NOTE2: Is making new Translation object inside the query method correct? I have some doubts, because this method is inside the Translations.class

Coderian
  • 23
  • 6

0 Answers0