我需要执行一个 Volley 请求并等待响应来解析它并返回它,但不知道如何实现这一点。 有人可以帮忙吗? 这是我的代码:
public void getWord(){
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (lesMots.get(key) instanceof JSONObject) {
JSONObject obj = (JSONObject) lesMots.get(key);
//Récupération des deux mots, anglais et français
String wordToFind = obj.getString("wordFrench").toUpperCase();
String wordEnglish = obj.getString("wordEnglish").toUpperCase();
//Mots mis dans un array respectif
listOfWordEnglish.add(wordEnglish);
listOfWordFrench.add(wordToFind);
container.removeAllViews();
}
numberOfWord++;
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error + "", Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
每个数组中有 7 个单词,但是当我试图访问我的 initGame 函数时,它说它们是空的,我猜这是因为 volley 请求不是那么快! 如果有人可以向我解释该怎么做
这是我的 initGame 函数
`public void initGame() {
win = false;
found = 0;
typed_word.setText("");
image.setBackgroundResource(R.drawable.first);
listOfLetters = new ArrayList<>();
listOfWordFrench = new ArrayList<>();
listOfWordEnglish = new ArrayList<>();
getWord();
for (int i = 0; i < listOfWordEnglish.size(); i++){
System.out.println(i);
String wordEnglish = listOfWordEnglish.get(i);
wordEnglishPendu.setText(wordEnglish);
word = listOfWordFrench.get(i);
for (int x = 0; x < word.length(); x++) {
TextView oneLetter = (TextView) getLayoutInflater().inflate(R.layout.textview, null);
container.addView(oneLetter);
}
}
}`
最佳答案
由于Volley
是异步的,所以getWord()
下面的for
循环会在onResponse
之前被调用您的 Volley 请求。
您的问题的解决方案是将 for
循环移动到 onResponse
中,在那里您可以将它放在 while
循环之后。
希望对您有所帮助!
关于Android - 等待 Volley 响应完成并继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079491/