简体   繁体   English

方法不返回任何东西

[英]Method does not return anything

I have a java class containing a method CheckForUpdate() that has a return type of String . 我有一个包含方法CheckForUpdate()的Java类,该方法的返回类型为String Call to this method is initiated from my activity class . 从我的activity class开始对此方法的调用。 This method assigns the fetched String value to my class variable named link . 此方法将获取的String值分配给名为link class变量。 Inside the if block variable link shows the fetched String . if块变量link内部显示了提取的String But in the return statement it returns null . 但是在return语句中,它返回null Why is that? 这是为什么?


Java Class: Java类:

public class method_class {

    Context context;

    public String link;
    boolean b;

    public FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    public FirebaseFirestore firestore = FirebaseFirestore.getInstance();

    //constructor
    public method_class(Context context)
    {
        this.context = context;
    }

    public String CheckForUpdate()
    {
        firestore.collection("Admin").document("appinfo")
                .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                if(task.isSuccessful())
                {
                    DocumentSnapshot documentSnapshot = task.getResult();

                    String version = documentSnapshot.getString("version");

                    final String in_app_version = BuildConfig.VERSION_NAME;

                    if(!TextUtils.equals(version, in_app_version))
                    {
                        //update available
                        link = documentSnapshot.getString("link");
                    }
                    else
                    {
                        //no update
                        link = null;
                    }
                }
                else
                {
                    Toast.makeText(context, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });

        return link;
    }
}

Firebase methods are asynchronous, your method is basically returning the result before the listener fetches an event. Firebase方法是异步的,您的方法基本上是在侦听器获取事件之前返回结果。 Instead you should use the result once your onComplete fires with successful task instead of returning a String with the method 相反,一旦onComplete成功执行任务后就应使用结果,而不是使用方法返回String

You are using listener to read data. 您正在使用侦听器读取数据。 So your method returns link with null value before listener finishes data reading. 因此,在侦听器完成数据读取之前,您的方法将返回具有空值的链接。 You should wait listener then return link. 您应该等待侦听器,然后返回链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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