【问题标题】:String Array Inside Response Listener Gives Null values outside the Listener Class响应侦听器内部的字符串数组在侦听器类外部给出 Null 值
【发布时间】: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


【解决方案1】:

强排序,可以轻松正确地填充您的 UI 从网络异步获取数据。

Volley 发出异步请求,这意味着它在请求结束之前不会阻塞主线程,因此textView2.setText 将在str 数组填充数据之前执行。你需要把它放在onResponse里面

【讨论】:

  • 那么如果我必须将 str[] 数组发送到 listView,我应该在 onResponse 中声明 listview 怎么办,即 ListView= new ArrayAdapter(this,str); onResponse() 内部
  • 您有 2 个选择:第一:您所说的,因此您可以在 onresponse 方法中完成所有列表视图工作。其次,您在 onresponse 方法之外进行 lisview 工作,然后在 onresponse 中调用 notifyDataSetChanged()
猜你喜欢
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 2018-03-24
  • 1970-01-01
  • 2012-05-20
相关资源
最近更新 更多