方法不会更改全局变量值

时间:2019-07-16 21:53:20

标签: java android

我试图通过全局变量从内部方法中提取值,但是我无法从方法访问任何全局变量,只是我想从方法中获取值到onCreate方法!

从内部方法获取价值。

public class MainActivity extends AppCompatActivity {

    FirebaseFirestore db;
    //TextView  txtv;

    double tt = 55d;

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

        db = FirebaseFirestore.getInstance();
        //txtv = (TextView) findViewById(R.id.txt);


            //should print value of 'lat' >> 33
            //but it print original value of tt >> 55
            // I just want value of variable 'lat' here
          System.out.println(ReadSingleContact(1));

    }

    public double ReadSingleContact(int x ) {
        String num = Integer.toString(x);
        DocumentReference contact = db.collection("MAPS").document(num);
        contact.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task ) {
                if(task.isSuccessful()){
                    DocumentSnapshot doc = task.getResult();
                    /*
                    StringBuilder data = new StringBuilder("");
                    data.append("name: ").append(doc.getString("name"));
                    data.append("\nlatitude: ").append(doc.getString("latitude"));
                    data.append("\nlongtude: ").append(doc.getString("longtude"));

                    */
                    GeoPoint geoPoint = doc.getGeoPoint("latitude");
                    final double lat = geoPoint.getLatitude();
                    final double lng = geoPoint.getLongitude();

                    //let say lat = 33
                    tt = lat;

                }
            }
        });
        return tt;
    }

}

没有语法错误,只是变量“ tt”不会改变?

1 个答案:

答案 0 :(得分:0)

编辑-如果您打算在多个地方使用该函数并需要使用结果,则需要使用回调从异步调用中获取结果(实际上,您可以已经为contact.get()使用了回调。您需要按照以下几行重构代码。

为接口创建一个Java文件。

public interface CustomCallback {
    void onComplete(double lat, double lng);
}

使用接口作为函数的参数,在获得onCompletelat的值之后调用lng

public class MainActivity extends AppCompatActivity {
    FirebaseFirestore db;
    TextView  txtv;
    double tt ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = FirebaseFirestore.getInstance();
        txtv = (TextView) findViewById(R.id.txt);
        //txtv.setText(ReadSingleContact(1)+"A");
        //Here you can call the function and implement the interface method that'll get called once the values for lat & lng are calculated
        ReadSingleContact(1, new CustomCallback() {
            @Override
            public void onComplete(double lat, double lng) {
                //here you can implement your required code
                //which can be changed based on what calls this method
                txtv.setText(lat+"A");
                //P.S - At this point, the value of tt would have been changed, since the `onComplete` method gets called after the value of tt is changed.
            }
        });
    }
    public void ReadSingleContact(int x, CustomCallback customCallback) {
        String num = Integer.toString(x);
        DocumentReference contact = db.collection("MAPS").document(num);
        contact.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task ) {
                if(task.isSuccessful()){
                    DocumentSnapshot doc = task.getResult();
                    /*
                    StringBuilder data = new StringBuilder("");
                    data.append("name: ").append(doc.getString("name"));
                    data.append("\nlatitude: ").append(doc.getString("latitude"));
                    data.append("\nlongtude: ").append(doc.getString("longtude"));
                    */
                    GeoPoint geoPoint = doc.getGeoPoint("latitude");
                    double lat = geoPoint.getLatitude();
                    double lng = geoPoint.getLongitude();
                    tt = 22;
                    //Call customCallback.onComplete at the end
                    if (customCallback != null) {
                        customCallback.onComplete(lat,lng);
                    }
                }
            }
        });
    }
}

contact.get()是一个异步调用,因此tt = 22;很可能仅在return tt;之后出现。如果您只想在textview中设置纬度和经度值,请在回调中进行设置。

public class MainActivity extends AppCompatActivity {
    FirebaseFirestore db;
    TextView  txtv;
    double tt ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = FirebaseFirestore.getInstance();
        txtv = (TextView) findViewById(R.id.txt);
        //txtv.setText(ReadSingleContact(1)+"A");
    }
    public double ReadSingleContact(int x ) {
        String num = Integer.toString(x);
        DocumentReference contact = db.collection("MAPS").document(num);
        contact.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task ) {
                if(task.isSuccessful()){
                    DocumentSnapshot doc = task.getResult();
                    /*
                    StringBuilder data = new StringBuilder("");
                    data.append("name: ").append(doc.getString("name"));
                    data.append("\nlatitude: ").append(doc.getString("latitude"));
                    data.append("\nlongtude: ").append(doc.getString("longtude"));

                    */
                    GeoPoint geoPoint = doc.getGeoPoint("latitude");
                     double lat = geoPoint.getLatitude();
                    double lng = geoPoint.getLongitude();
                   //value dose not changed ??!
                    tt = 22;
                    runOnUiThread(new Runnable() {
                         void run() {
                             txtv.setText(tt+"A");
                             txtv.setText(lat+","+lng);
                         }
                    });
                }
            }
        });
        return tt;
    }
}