简体   繁体   中英

Method won't change global variable value

I tried to extract value from inner method by global variable, but i cant access to any global variable from method, just i want to get the value from method to onCreate method!

Get value from inner method to another.

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;
    }

}

no syntax error, just variable 'tt' dose not change ?

Edit - If you intent to use the function in multiple places and need to use the result, then you'll need to get the result from the asynchronous call using a callback (infact, you're already using a callback for contact.get() ). You'll need to refactor your code along the following lines.

Create a java file for the interface.

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

Use the interface as an argument to your function, call the onComplete after you get the values of lat & 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);
                    }
                }
            }
        });
    }
}

The contact.get() is an asynchronous call, so tt = 22; will likely only occur after return tt; . If you simply want to set the latitude and longitude value in the textview, then do so in the callback.

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;
    }
}

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