-1

Dears,

Take a look at the codes below...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    url = "http://xxxxxxx/getAllQuestionsByDate.php"


    System.out.println(useData());
}


public ArrayList<QuestionsModel> useData() {


    ArrayList<QuestionsModel> Temp_List_Of_Model_Objects = new ArrayList<>();

    DownloadJson jsonn = new DownloadJson();

    jsonn.GetAllQuestionsByDate(url, new JsonCallback() {

        @Override
        public void onNetworkCallFinished(final JSONObject jsonResponse) {

           try {
                JSONArray arryKey = jsonResponse.getJSONArray("questions");
                int jsonArrayObjectsCount = arryKey.length();

                    for (int i=0; i < jsonArrayObjectsCount; i++){
                        JSONObject ArrayRow = arryKey.getJSONObject(i);

                        int qid = ArrayRow.getInt("QID");
                        String question_text = ArrayRow.getString("Question");
                        int questionType = ArrayRow.getInt("Question_Type");
                        String question_image_url = ArrayRow.getString("Question_Img");
                        String question_date_inserted = ArrayRow.getString("Question_Insert_Date");

                        QuestionsModel question = new QuestionsModel(qid, question_text, questionType, question_image_url, question_date_inserted);
                        Temp_List_Of_Model_Objects.add(question);
                    }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            //System.out.println(List_Of_Model_Objects.get(0).getQuestion_text());


        }
    });

    return Temp_List_Of_Model_Objects;
}

When calling useDate() in OnCreate method, it is returning an empty array []. Why is that? It should be populated with ArrayList data. Am i missing something? According to some debugging, i noticed that the array is populated and then destroyed after 'onNetworkCallFinished' is finished being called.

Aboodnet
  • 143
  • 15

1 Answers1

0

It seems that jsonn.GetAllQuestionsByDate(...) is an async call.

To more precise details:

Methods (specially those which do I/O or network actions) could be called synchronously or asynchronously. Synchronous call means that your current thread will be block until called method finish its work and return. Asynchronous call means that your thread will not block and continue to do remain code, in such case a callback will be existed which is informed when asynch method call returns. For more info see asynchronous vs synchronous execution.

In your code it seems you call an async call and then immediately return from caller method. In this state you may return an empty list because asynch method does not provide result to Temp_List_Of_Model_Objects yet.

hadi.mansouri
  • 828
  • 11
  • 25