I am trying to fetch data from my website and store it in an Array. And I did it successfully but why I can’t use the Array from outside the JSONArray Request Method. I want to return the 2d Array from my method but it showing me error. I also tried some other ways but in the end I am not able to get any data from the Arrays inside the JSONArray Request Method.
public String[][] QuestionAns(){
String url = "https://testing.testing/q-bank/QnA.php?category=" + this.subject + "&&STD=" + this.std;
String[] questions = new String[10];
String[] options1 = new String[10];
String[] options2 = new String[10];
String[] options3 = new String[10];
String[] options4 = new String[10];
String[] answers = new String[10];
RequestQueue queue = Volley.newRequestQueue(this.context);
Toast.makeText(this.context, "Check", Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, response -> {
try {
JSONArray questionArr = response.getJSONArray("question");
JSONArray option1Arr = response.getJSONArray("option1");
JSONArray option2Arr = response.getJSONArray("option2");
JSONArray option3Arr = response.getJSONArray("option3");
JSONArray option4Arr = response.getJSONArray("option4");
JSONArray answerArr = response.getJSONArray("answer");
for (int i = 0; i<questionArr.length(); i++){
questions[i] = questionArr.getString(i);
options1[i] = option1Arr.getString(i);
options2[i] = option2Arr.getString(i);
options3[i] = option3Arr.getString(i);
options4[i] = option4Arr.getString(i);
answers[i] = answerArr.getString(i);
}
String [][] QnA = {questions, options1, options2, options3, options4, answers};
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Toast.makeText(context, "Something Went Wrong...", Toast.LENGTH_SHORT).show());
queue.add(jsonObjectRequest);
return QnA;
}
2
Answers
You cannot use variables defined in inner scope in outer scope. In this case QnA in defined in
response -> {}
lambda, and it’s not visible in QuestionAns() method.Moreover, in lambda you cannot modify outer references (outer variables used in lambda need to be effectively final).
I suggest this.
final List QnA
as list of lists.First of all, you can’t access variables defined outside the scope. Also if you declare the
Qna
inside the scope, It will still return an empty array because the request takes some time for response.In order to get the array, you have to use a method called after the response.
like