【发布时间】:2017-12-31 02:20:34
【问题描述】:
我正在通过 JSONObject 从远程服务器获取数据。问题是,当我尝试将响应字符串保存到字符串数组中以供在响应侦听器之外使用时,字符串数组会给出空值。我应该怎么做才能使我从远程服务器获得的字符串可以在响应侦听器之外。
主要活动。 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 值..
【问题讨论】:
-
在您的代码中,您只需将数据分配给 textview1 和数组中的第一个索引。您没有为 textview2 分配任何值
标签: java android xml android-volley