无法在Android Java中分配值

时间:2019-06-17 13:34:45

标签: java android firebase google-cloud-firestore

我正在尝试分配{ "@odata.context": "http://api.powerbi.com/v1.0/myorg/$metadata#datasources", "value": [] } 下的文档计数值。我正在分配给变量i。但是在firebase firestore中,它给了我正确的值,但是当我将变量赋给变量i并在下面使用它时,它仍然给出了logcat

下面是代码

value 0

需要帮助以获取正确的i值。

我当前的替代工作代码,即在onCompleteListener内部执行操作。但是我觉得这不是最好的解决方案

public class FirestoreNew extends AppCompatActivity {

    FirebaseAuth mAuth;
    FirebaseFirestore mfirebasefs = FirebaseFirestore.getInstance();
    DocumentReference AllUserInfo_doc, AllTicketData_doc, AllPassesData_doc;
    CollectionReference UserData, TicketData, PassData;
    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firestore_new);

        //Auth Purpose
        mAuth = FirebaseAuth.getInstance();

        //Document Reference
        AllUserInfo_doc = mfirebasefs.collection(mAuth.getCurrentUser().getEmail())
                .document("AllUserData");
        AllTicketData_doc = mfirebasefs.collection(mAuth.getCurrentUser().getEmail())
                .document("AllTicketsData");
        AllPassesData_doc = mfirebasefs.collection(mAuth.getCurrentUser().getEmail())
                .document("AllPassesData");

        //Collection Reference
        UserData = AllUserInfo_doc.collection("UserDataCollection");
        TicketData = AllTicketData_doc.collection("TicketsList");
        PassData = AllPassesData_doc.collection("PassesList");



       TicketData.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    Log.d("TAG", task.getResult().size() + "");
                    i = task.getResult().size();
                } else {
                    Log.d("TAG", "Error getting documents: ", task.getException());
                }
            }
       });


       i = i + 1;
       String s = "Ticket" + i;
        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
        //Documents
        DocumentReference myTicket = TicketData.document(s);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("Ticket Number", "TEST123");
        map1.put("FROM","FROM PLACE");

        myTicket.set(map1);



    }
}

1 个答案:

答案 0 :(得分:2)

您的onCompleteListener正在异步工作,这意味着(通常)在i获得赋值之前,代码i = i+1已经结束。您应该坚持解决方法,这实际上是一个有效的解决方案。干杯!