如何在下面的 onResponse() 回调中设置局部变量 publicIpAddress? “publicIpAddress = response”行有错误“无法分配最终局部变量 publicIpAddress,因为它是在封闭类型中定义的”
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;
}
最佳答案
绝对不推荐这样做。您发出的请求是异步的,并且将始终返回 null 或 ""- 无论您使用什么值初始化 publicIpAddress。 您的方法在将 StringRequest 放入队列后立即返回,然后才有机会执行 onResponse 方法。返回发生在调用此代码之前:publicIpAddress = response;
关于java - 如何在 Java/Android 的回调函数中设置局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307904/