如何在 Java / Android 回调函数中设置局部变量?

How to set local variable inside callback function in Java / Android?

如何在下面的 onResponse() 回调中设置局部变量 publicIpAddress? "publicIpAddress = response"行有错误"final local variable publicIpAddress cannot be assigned, since it is defined in an enclosing type"

public static String getPublicIpAddress(Context context)
    {
        String publicIpAddress = "";

        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, 
                                                                    "http://icanhazip.com/", 
                                                                    new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                publicIpAddress = response;
            }                       
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error in getPublicIpAddress()");
            }
        });

        VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

        return publicIpAddress;
    }

final 变量只能初始化一次。参见 How final keyword works

在您的情况下,您在声明中(final String publicIpAddress = ""; 和 OnResponse)初始化了 2 次。

尝试: 1)去掉关键字final 2) 去掉publicIpAddress

声明中的初始化

好的,就这样吧

public class xxxx  extends Activity {

  static String publicIpAddress;
................................

public static String getPublicIpAddress(Context context)
    {

        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, 
                                                                    "http://icanhazip.com/", 
                                                                    new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                publicIpAddress = response;
            }                       
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error in getPublicIpAddress()");
            }
        });

        VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

        return publicIpAddress;
    }

绝对不推荐。您发出的请求是异步的,并且始终 return null 或 "" - 无论您使用什么值初始化 publicIpAddress。 您的方法在将 StringRequest 放入队列后立即 returning,然后才有机会执行 onResponse 方法。 return 发生在调用此代码之前:publicIpAddress = response;

读这个:Asynchronous HTTP Requests in Android Using Volley