【问题标题】:Fetch JSON Array to ArrayList to ListView获取 JSON 数组到 ArrayList 到 ListView
【发布时间】:2018-01-24 06:44:34
【问题描述】:

我有一个 php 页面 (urldisplay) 返回这个问题对象数组:

[{
"suggestid": "1",
"question": "What does Aotearoa mean?",
"answer1": "Maui and the Whale",
"answer2": "2 Islands",
"answer3": "Land of the Long White Cloud",
"answer4": "Isle of Greenstone",
"correctanswer": "Land of the Long White Cloud",
"userID": "1"
 }, {
"suggestid": "2",
"question": "What does Haere Ra mean?",
"answer1": "Hello",
"answer2": "Goodbye",
"answer3": "Thanks",
"answer4": "Sorry",
"correctanswer": "Goodbye",
"userID": "1"
}, {
"suggestid": "3",
"question": "Where is Zealand?",
"answer1": "France",
"answer2": "Germany",
"answer3": "Denamrk",
"answer4": "Finland",
"correctanswer": "Denmark",
"userID": "1"
}, {
"suggestid": "4",
"question": "What does Aotearoa mean?",
"answer1": "Maui and the Whale",
"answer2": "2 Islands",
"answer3": "Land of the Long White Cloud",
"answer4": "Isle of Greenstone",
"correctanswer": "Land of the Long White Cloud",
"userID": "2"
  }, {
"suggestid": "5",
"question": "What does Aotearoa mean?",
"answer1": "Maui and the Whale",
"answer2": "2 Islands",
"answer3": "Land of the Long White Cloud",
"answer4": "Isle of Greenstone",
"correctanswer": "Land of the Long White Cloud",
"userID": "3"
}]

我正在尝试通过此类(在我的 DAO 类中)读取对象,它将结果保存到问题数组列表中

ArrayList<Question> quest;

    public ArrayList<Question> ListSugg()
{
    ListSuggestions sugg = (ListSuggestions)new ListSuggestions().execute();
    return quest;
}

public class ListSuggestions extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL(urldisplay);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            JSONArray jsonArray = new JSONArray(con);
            quest = new ArrayList<Question>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String question = jsonObject.getString("question");
                String answer1 = jsonObject.getString("answer1");
                String answer2 = jsonObject.getString("answer2");
                String answer3 = jsonObject.getString("answer3");
                String answer4 = jsonObject.getString("answer4");
                String correctanswer = jsonObject.getString("correctanswer");
                Question ques = new Question(0, question, answer1, answer2, answer3, answer4, correctanswer);
                quest.add(ques);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        return null;
    }
}

任务仍然是空的。然后我想将问题对象添加到 ListView。

public class ListActivity extends AppCompatActivity {
ListView listv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    listv = (ListView)findViewById(R.id.ListDisplay);
    DAO dao = new DAO();
    ArrayList list = dao.ListSugg();
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            list );

    listv.setAdapter(arrayAdapter);
}

我已经尝试了很多其他 SO 帖子,但我似乎在追赶我的尾巴。谁能发现我的错误/我有更好的方法吗?

干杯,

【问题讨论】:

  • 您遇到了什么错误?
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.
  • jsonarray 为空,因此在 for 循环中失败

标签: java php android json listview


【解决方案1】:

问题是 AsyncTask 执行代码 Asunchrounsly,这意味着当你调用 ListSugg() 时,它会在另一个线程上运行后台任务,并在后台任务完成之前返回任务对象,这意味着你会有一个静止的空列表。 read here for more info

您可以做的是覆盖onPostExecute 方法,并在那里设置适配器,如下所示:

public class ListSuggestions extends AsyncTask<Void, Void, Void> {

    @Override
    protected Boolean doInBackground(String... params) {
        // do something
        return true;
    }

    @Override
    protected void onPostExecute(String result) {
        // The results of the above method
        // Processing the results here

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
             this,
             android.R.layout.simple_list_item_1,
             list);

        listv.setAdapter(arrayAdapter);

    }

}

但要使其正常工作,您需要将 AsyncTask 包含在 MainActivity 中。

这应该可以解决您的问题,希望对您有所帮助。

但是,还有更好、更简单的解决方案,例如使用 okhttp 或 Retrofit 等 HTTP 网络库,以及使用 Gson 等 JSON 解析器,如果您愿意,可以查看它们。

【讨论】:

    【解决方案2】:

    您在触发后台任务后立即返回ques。后台任务需要一些时间才能完成,在此之前您的 ques 列表将保持为空,因此您将看不到数据。

    更新 AsyncTask 的 postExecute 方法中的列表。

    【讨论】:

      【解决方案3】:

      试试这个

              quest = new ArrayList<Question>();
              for (int i = 0; i < jsonArray.length(); i++) {
      
                  JSONObject jsonObject = jsonArray.getJSONObject(i);
      
                  Question ques = new Question(); //inti Question
                  //Enter Values to Question Object
                  ques.setQuestion( jsonObject.getString("question"));
                  ques.setAnswer1( jsonObject.getString("answer1"));
                  ques.setAnswer2( jsonObject.getString("answer2"));
                  ques.setAnswer3( jsonObject.getString("answer3"));
                  ques.setAnswer4( jsonObject.getString("answer4"));
                  ques.setCorrectAnswer( jsonObject.getString("correctanswer"));
                  // Add Question Object to ArrayList
                  quest.add(ques);
              }
      

      【讨论】:

        【解决方案4】:

        它是空的,因为您从 doInBackground() 返回 null。理想的方法是将结果传递给 onPostExecute() 并在那里设置适配器。像这样:-

        public class ListSuggestions extends AsyncTask<Void, Void, ArrayList<Question>> {
        
            @Override
            protected ArrayList<Question> doInBackground(Void... params) {
        
                try {
                    URL url = new URL(urldisplay);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    //JSONArray jsonArray = new JSONArray(con);
                    quest = new ArrayList<Question>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String question = jsonObject.getString("question");
                        String answer1 = jsonObject.getString("answer1");
                        String answer2 = jsonObject.getString("answer2");
                        String answer3 = jsonObject.getString("answer3");
                        String answer4 = jsonObject.getString("answer4");
                        String correctanswer = jsonObject.getString("correctanswer");
                        Question ques = new Question(0, question, answer1, answer2, answer3, answer4, correctanswer);
                        quest.add(ques);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                return quest;
            }
        
            @Override
            protected void onPostExecute(ArrayList<Question> questions) {
                super.onPostExecute(questions);
        
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                        this,
                        android.R.layout.simple_list_item_1,
                        list );
        
                listv.setAdapter(arrayAdapter);
            }
        } 
        

        【讨论】:

          猜你喜欢
          • 2016-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多