简体   繁体   中英

cloud firestore using server

I am using Cloud Firestore as my database for an android project. I am writing all the crud operations in the app which makes it very slow and the code is large. I want to shift all the code to the server and make only API calls using the app.

for example,

public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
    List<String> usersf = new ArrayList<>();

    for (DocumentSnapshot doc : queryDocumentSnapshots) {
        usersf.add(doc.getId());

    }

    fi.onFollowingRetrieved(usersf);
}

here I write this code in my app, which get me a list of user id. I want to write an api in my application which fetches this list from server and do not do the work itself.

how do I implement this?

I mean I don't want to run the loop in my app but on the server and want the server to just send me the list.

In that case, you should map the QuerySnapshot object directly into a List of custom objects. Assuming that you have a class that is similar to this one:

public class User {
    public String uid;
    public String name;
    public String email;

    public User() {}

    User(String uid, String name, String email) {
        this.uid = uid;
        this.name = name;
        this.email = email;
    }
}

To remove the for loop and get directly get the list, please use the following lines of code:

public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
    fi.onFollowingRetrieved(queryDocumentSnapshots.toObjects(User.class));
}

See, I have used QuerySnapshot# toObjects(@NonNull Class clazz) which:

Returns the contents of the documents in the QuerySnapshot, converted to the provided class, as a list.

Be also aware that the more documents your query returns, the longer the reading time will be. There's no hack for that, other than limiting the results .

If you only want the document IDs, then assuming that the document ID is represented by the UID, then you should simply use the following code:

public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
    List<User> users = queryDocumentSnapshots.toObjects(User.class);
    List<String> usersf = users.stream().map(user -> user.uid).toList()
    fi.onFollowingRetrieved(usersf);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM