问题
All of the text in an application I'm working on is stored inside FireStore documents, so to retrieve it I use this bit of code
db.collection("language").document("kCreateNewAccount").get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String viewText = lan.equals("en") ? documentSnapshot.getString("en")
: documentSnapshot.getString("es");
createAccount.setText(viewText);
}
});
I've tried to put it into a function that takes the document name as a parameter and returns the correspondent string to avoid writing the same thing over and over again, to no avail, any help is welcome
回答1:
Firebase queries are async, you have to use a callback function.
Create Interface for callback
public interface OnCompleteListener { void onComplete(String text); }Create method for fetching text via document name
public void getText(String document, final OnCompleteListener onCompleteListener) { db.collection("language").document(document).get() .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { String viewText = lan.equals("en") ? documentSnapshot.getString("en") : documentSnapshot.getString("es"); onCompleteListener.onComplete(viewText); } }); }Call the method with your document name and specifying a listener
getText("kCreateNewAccount", new OnCompleteListener() { @Override public void onComplete(String text) { createAccount.setText(text); } });
来源:https://stackoverflow.com/questions/62482282/is-there-a-way-to-write-this-database-call-into-a-function-easily