gpt4 book ai didi

java - 响应监听器内部的字符串数组在监听器类外部提供空值

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

我正在通过 JSONObject 从远程服务器获取数据。问题是,当我尝试将响应字符串保存到字符串数组中以供在响应监听器外部使用时,字符串数组会给出空值。我应该怎么做才能使我从远程服务器获得的字符串可以在响应监听器之外。

主要 Activity 。 java代码如下

   public class MainActivity extends Activity {
MySingleton singleton;
TextView textView;
TextView textView2;

Button button;
RequestQueue rqueue;

final String url="http://www.muftiattaullahmultani.com/greeting.php";

public static int count=0;

public final String[] str=new String[2];

public String s;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


textView=(TextView) findViewById(R.id.textView);
textView2=(TextView) findViewById(R.id.textView2);
JsonArrayRequest jsonObjectRequest= new
JsonArrayRequest(Request.Method.POST, url, null, new
Response.Listener<JSONArray>() {

public void onResponse(JSONArray response) {

while(count<response.length())
{
JSONObject object= null;
try {
object = response.getJSONObject(count);
String s = object.getString("id") +" "+ object.getString("name")+" " + object.getString("password");
str[0]=s;
textView.setText(str[0]);
count++;
} catch (JSONException e) {
e.printStackTrace();
}


}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("ERROR");
}
});







MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);

textView2.setText(str[0]);

}}

TextView 1 给出了正确的值,但 textview2 给出了 NuLL 值..

最佳答案

Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.

Volley 进行异步请求,这意味着它不会阻塞主线程直到请求结束,所以 textView2.setText 将在 之前执行str 数组填充了数据。你需要把它放在 onResponse

里面

关于java - 响应监听器内部的字符串数组在监听器类外部提供空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298515/

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