我使用" token",ValueContainer类的实例声明为final,以便保存从JSON请求接收的数据。在匿名函数Response.Listener()中,我设置了令牌的值,它可以工作。
Log.d("myTag", "token value1:" + token.getValue());
此行显示正确的值(非null)。但是,当我再次检查token.getValue()的值时(这次是在匿名函数之外)
Log.d("myTag", "token value2:" + token.getValue());
我得到了token.getValue()= null。我不明白为什么令牌的值似乎被重置为空。我错过了什么吗?
完整代码:
public class MainActivity extends AppCompatActivity {
class ValueContainer<T> {
private T value;
public ValueContainer() { }
public ValueContainer(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ValueContainer<String> token = new ValueContainer<String>();
String getTokenUrl = "http://www.someurl.com/?somekey=somevalue";
JsonObjectRequest getTokenRequest = new JsonObjectRequest(
Request.Method.GET, getTokenUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
token.setValue(response.getString("token"));
Log.d("myTag", "token value1:" + token.getValue());
mainTextView.append("Response: JsonObjectRequest successful: get_token: " + token.getValue() + "\n");
} catch (JSONException e) {
mainTextView.append("Response: JSONException: getString():" + e);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mainTextView.append("Response: JsonObjectRequest failed: " + error + "\n");
}
});
Log.d("myTag", "token value2:" + token.getValue());
}
答案 0 :(得分:1)
您可以更改&#34;真实内容&#34;一个&#34;最终&#34;对象,但你不能改变它的地址,正如例子所说的那样。
String stringTest = "test String";
StringBuffer normalTest = new StringBuffer(stringTest);
normalTest = normalTest.append(" end");
normalTest.delete(0, 5);
System.out.println(normalTest);
final StringBuffer finalTest = new StringBuffer(stringTest);
// finalTest = finalTest.append(" end"); // can't work;
finalTest.delete(0, 5);
System.out.println(finalTest);
您可以按照代码进行测试
//token = new Token("...")// can't work
token.changeTheToken("...")// work ok