Android无法从其他功能返回值[Sync Volley]

时间:2017-06-17 00:22:33

标签: java android android-volley

亲爱的,

看看下面的代码......

@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;
}

在OnCreate方法中调用useDate()时,它返回一个空数组[]。这是为什么?它应该填充ArrayList数据。我错过了什么吗?根据一些调试,我注意到阵列已经填充,然后在“网络呼叫完成”之后被销毁。结束了。

1 个答案:

答案 0 :(得分:0)

似乎jsonn.GetAllQuestionsByDate(...)是异步调用。

更准确的细节:

可以同步或异步调用方法(特别是那些执行I / O或网络操作的方法)。同步调用意味着您的当前线程将被阻塞,直到被调用的方法完成其工作并返回。异步调用意味着您的线程不会阻塞并继续执行保留代码,在这种情况下将存在回调,当回转异步方法调用时会通知回调。有关详细信息,请参阅asynchronous vs synchronous execution

在您的代码中,您似乎调用异步调用,然后立即从调用方法返回。在此状态下,您可能返回一个空列表,因为asynch方法尚未向Temp_List_Of_Model_Objects提供结果。