gpt4 book ai didi

java - 如何将响应存储在 Volley 的变量中?

转载 作者:行者123 更新时间:2023-11-30 05:00:59 25 4
gpt4 key购买 nike

我想将 Volley 的响应存储在一个公共(public)变量中,但是当我将它烤出来时,返回 null 的 volley 请求

public  JSONArray array ;
String URL = "http://192.168.1.104/json.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);

array = new JSONArray();

JsonArrayRequest request = new JsonArrayRequest( URL,new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {

try {
array = response;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});
Volley.newRequestQueue(this).add(request);

Toast.makeText(json.this, array.toString(),Toast.LENGTH_LONG).show();

最佳答案

正如人们所说,在 onResponse() 中调用 Toast 启动是可行的,但是最佳处理此问题的方法是创建一个小的监听器接口(interface)或方法,在 onResponse 中调用并在您的位置实现需要它。

我还强烈建议只传递您需要的数据并将其保存在模型类中,而不是直接保存响应。

一个非常简单的例子是

String URL = "http://192.168.1.104/json.php";

// make sure your class implements this
public interface ResponseListener {
public gotResponse(JSONArray array);
}

// implementation of ResponseListener
public gotResponse(JSONArray array) {
// eventually do more with this data
Toast.makeText(json.this, array.toString(),Toast.LENGTH_LONG).show();
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);

ResponseListener listener = this;

JsonArrayRequest request = new JsonArrayRequest( URL,new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {

try {
listener.gotResponse(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});
Volley.newRequestQueue(this).add(request);

关于java - 如何将响应存储在 Volley 的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com