如何在android中使JSONarray为null?

时间:2015-03-25 07:09:00

标签: android asynchronous pull-to-refresh

我正在构建一个Android应用程序,其中有一个主屏幕,其中onCreate我正在初始化异步任务。在该异步任务中,我从服务器获取数据并使用baseAdapter显示。

现在的问题是刷新我再次触发Async任务而且它复制了我的数据因此,我需要使用BaseAdapter将旧数据删除并将新数据插入到列表中。

这是制作异步任务 -

 /**
 * Async task class to get json by making HTTP call
 */
private class questionfeed_async extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

    }


    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        ServiceHandler http = new ServiceHandler();
        jsonString = http.makeServiceCall(url, ServiceHandler.GET,
                null);
        if (jsonString != null) {
            try {
                SCROLL_TO_POSITION = currentQuestionArray.length();
                questions = new JSONArray(jsonString);
                //result_text = new String[questions.length()];

                for (int i = 0; i < questions.length(); i++) {
                    temp_obj = questions.getJSONObject(i);


                    JSONObject currentQuestionObject = new JSONObject();

                    currentQuestionObject.put("question_text", temp_obj.getString(Tag_questionText)
                            .toString());

                    currentQuestionArray.put(currentQuestionObject);

                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        } else {
            Log.d("TAG", "Empty");
        }
        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);


            adapter = new BaseAdapterFeed(getActivity(), currentQuestionArray);

            questionfeed_customelistview.setAdapter(adapter);               

        } catch (NullPointerException e) {
            // probably don't bother doing clean up
        } finally {
            // carry on as if nothing went wrong
        }


    }

2 个答案:

答案 0 :(得分:0)

我认为问题出在&#34; currentQuestionArray&#34;。你必须每次创建新的。与doInBackground方法中的currentQuestionArray=new HashMap<String,String>()类似。问题是每次在地图中插入新的currentQuestionObject但旧的也会保留。希望它能帮到你。

答案 1 :(得分:0)

在刷新期间创建新适配器,也是如上所述的新数组