如何在OnResponse方法外部访问响应值?

huangapple go评论97阅读模式
英文:

How to access response value out of OnResponse method?

问题

这是我的活动

public class Tmp2 extends AppCompatActivity {
    public RequestQueue queue;
    static ArrayList<Question> array_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tmp2);
        array_list = new ArrayList<>();
        queue = AppController.getInstance(this).getRequestQueue();
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
                "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json",
                (JSONArray) null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                Question question = new Question();
                                question.setAnswer(response.getJSONArray(i).get(0).toString());
                                question.setAnswertrue((Boolean) response.getJSONArray(i).get(1));
                                array_list.add(question);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        Log.d("wakwash", "array " + array_list.size());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        Log.d("json", "array " + array_list.size());
        queue.add(jsonArrayRequest);
        Log.d("json", "array " + array_list);
    }
}

Logcat:

2020-10-25 00:32:43.548 18576-18576/com.example.practice D/json: array 0
2020-10-25 00:32:43.548 18576-18576/com.example.practice D/json: array []

它显示数组的大小为零,其中没有元素,但是当我在 onResponse 中使用此日志时,它会同时提供大小和元素。如何在响应之外访问我的数组列表?

英文:

I want to see my array list in my logcat but when I run my app in logcat it shows that size of my array list is zero and there is no elements in it

this is my activity

   public class Tmp2 extends AppCompatActivity {
public RequestQueue queue;
static ArrayList&lt;Question&gt; array_list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tmp2);
array_list = new ArrayList&lt;&gt;();
queue= AppController.getInstance(this).getRequestQueue();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
&quot;https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json&quot;,
(JSONArray) null,
new Response.Listener&lt;JSONArray&gt;() {
@Override
public void onResponse(JSONArray response) {
for(int i=0;i&lt;response.length();i++) {
try {
Question question = new Question();
question.setAnswer(response.getJSONArray(i).get(0).toString());
question.setAnswertrue((Boolean) response.getJSONArray(i).get(1));
array_list.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}Log.d(&quot;wakwash&quot;,&quot;array &quot;+array_list.size());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Log.d(&quot;json&quot;,&quot;array &quot;+array_list.size());
queue.add(jsonArrayRequest);
Log.d(&quot;json&quot;,&quot;array &quot;+array_list);
}
}

Logcat:

2020-10-25 00:32:43.548 18576-18576/com.example.practice D/json: array 0
2020-10-25 00:32:43.548 18576-18576/com.example.practice D/json: array []

its showing that size of my array is zero and there is no element it but when i use this log in onResonse it gives sizeand elements both. How can I access my array list out of the response

答案1

得分: 1

因为您在错误的位置记录了数组大小,甚至在收到响应之前就进行了记录,您正在进行一个异步调用,但您编写的日志是以同步方式执行的,这将始终为空。当您收到响应时记录数据,即在onResponse回调中。

public class Tmp2 extends AppCompatActivity {
    public RequestQueue queue;
    static ArrayList<Question> array_list;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tmp2);
        array_list = new ArrayList<>();
        queue = AppController.getInstance(this).getRequestQueue();
        
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
            Request.Method.GET,
            "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json",
            (JSONArray) null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for(int i = 0; i < response.length(); i++) {
                        try {
                            Question question = new Question();
                            question.setAnswer(response.getJSONArray(i).get(0).toString());
                            question.setAnswertrue((Boolean) response.getJSONArray(i).get(1));
                            array_list.add(question);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.d("wakwash", "array " + array_list.size());
                    // 在这里记录日志
                    Log.d("json", "array " + array_list.size());                     
                    Log.d("json", "array " + array_list);
                }
            }, 
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
        
        // 日志从这里移除
        queue.add(jsonArrayRequest);
    }
}

在收到响应后执行您的工作,而不是在响应范围之外执行,您还可以为响应创建回调。

英文:

This is because you are logging your array size at wrong place even before you're getting the response, you are making a call which is asynchronous but the log that you've written is executed in synchronous manner that will always be empty.
Log your data when your response is received i.e in onResponse callback.

public class Tmp2 extends AppCompatActivity {
public RequestQueue queue;
static ArrayList&lt;Question&gt; array_list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tmp2);
array_list = new ArrayList&lt;&gt;();
queue= AppController.getInstance(this).getRequestQueue();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
&quot;https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json&quot;,
(JSONArray) null,
new Response.Listener&lt;JSONArray&gt;() {
@Override
public void onResponse(JSONArray response) {
for(int i=0;i&lt;response.length();i++) {
try {
Question question = new Question();
question.setAnswer(response.getJSONArray(i).get(0).toString());
question.setAnswertrue((Boolean) response.getJSONArray(i).get(1));
array_list.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}Log.d(&quot;wakwash&quot;,&quot;array &quot;+array_list.size());
// Log it over here
Log.d(&quot;json&quot;,&quot;array &quot;+array_list.size());                     
Log.d(&quot;json&quot;,&quot;array &quot;+array_list);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//Log removed from here
queue.add(jsonArrayRequest);
}
}

You have to do your work after the response is received rather than doing it outside of the response scope, You can also make a callback for your response.

huangapple
  • 本文由 发表于 2020年10月25日 03:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64517311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定