在方法内部更改局部变量,执行方法时变量不会更改

Change local variable inside method, when the method is executed the variable is not changed

我正在开发 android 应用程序。我有这种形式,当单击按钮时,它会执行一个名为 insertData() 的方法。在这个函数中,我用另一个函数 getAddress().

更改了一个名为 "address" 的局部变量

在函数 getAddress 中,局部变量 "address" 已成功更改。但是当我们进入函数insertData()时,变量"address"仍然包含本例中的旧数据"Location Unknown".

我在这里没有看到什么?

insertData()

public String address = "Location unknown";

public boolean insertData(String title, String description, String image, Double longitude, Double latitude, String date) {
    String location = Double.toString(longitude) + "," + Double.toString(latitude);
    getAddress(location);
    Log.d("TAG2", address); // Still "Location unknown"
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, title);
    contentValues.put(COL_3, description);
    contentValues.put(COL_4, image);
    contentValues.put(COL_5, longitude);
    contentValues.put(COL_6, latitude);
    contentValues.put(COL_7, date);
    contentValues.put(COL_8, address);
    long result = db.insert(TABLE_NAME, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;

}

getAddress()

    public void getAddress(String coordination) {

    String token = "{removed for a reason haha}";
    String url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + coordination + ".json?access_token=" + token;

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().url(url).build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()) {
                String data = response.body().string();
                JsonParser parser = new JsonParser();

                try {
                    JsonObject obj = (JsonObject) parser.parse(data);
                    JsonArray arr = obj.getAsJsonArray("features");
                    JsonObject objj = arr.get(2).getAsJsonObject();
                    String place = objj.get("place_name").getAsString();
                        address = place;
                        Log.d("TAG", address); // Gives an address
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

Logcat调试器

2019-06-15 20:12:58.968 31465-31465/com.example.triptracker D/TAG2: Location unkown
2019-06-15 20:12:59.269 31465-31569/com.example.triptracker D/TAG: Mountain View, California, United States

我无法将 onResponse() 方法更改为 return 字符串。我不知道为什么,但它是一个只读方法。

getAddress {已更改}

    public void getAddress(String coordination) {

    String token = "{empty}";
    String url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + coordination + ".json?access_token=" + token;

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().url(url).build();

    try (Response response = client.newCall(request).execute()) {
        String data = response.body().string();
        JsonParser parser = new JsonParser();

        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        JsonObject obj = (JsonObject) parser.parse(data);
        JsonArray arr = obj.getAsJsonArray("features");
        JsonObject objj = arr.get(2).getAsJsonObject();
        String place = objj.get("place_name").getAsString();
        address = place;
        Log.d("TAG", address);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

getAddress() 异步执行它的工作。到 getAddress() return 秒时,您的 HTTP 请求还没有完成,因此 address 还没有改变。

由于 insertData() 正在执行磁盘 I/O,您应该在其自己的后台线程上调用 insertData(),因此您不会在磁盘 UI 时冻结 UI =22=] 正在进行中。如果是这种情况,那么您可以同步使用 OkHttp,使用 execute() 而不是 enqueue()。这将使您拥有 getAddress() return 地址,因此您可以将其插入数据库。