android listView动态刷新

package com.example.fiz.myapplication;

/**
 * Created by Fiz on 16/3/21.
 * 和服务器进行通信
 */

import android.annotation.SuppressLint;
import android.app.LauncherActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.app.Activity;

import android.widget.SimpleAdapter;


import com.example.fiz.myapplogin.DjangoRestClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

@SuppressLint("ValidFragment")
public class Home extends Fragment {
    private String textString;
    private static final String Tag = "MainActivity";

    private ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();

    public Home(String textString) {
        this.textString = textString;
    }

    public static Home newInstance(String textString) {
        Home mFragment = new Home(textString);
        return mFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_page, container, false);
        final ListView listView = (ListView) view.findViewById(R.id.listView);
        try {
            getPublicTimeline();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final SimpleAdapter adapter = new SimpleAdapter(getActivity(), getData(), R.layout.home_page_text,
                new String[]{"news_title", "news_from", "news_judge","news_time"}, new int[]{R.id.news_title, R.id.news_from, R.id.news_judge,R.id.news_time});
        listView.setAdapter(adapter);

//        adapter.notifyDataSetChanged();///
        /**
         *事件监听
         */
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.notifyDataSetChanged();
                if ( ! arrayList.get(position).equals(null)){
                    Log.d(Tag, "THIS IS A JOKKE AA  UN FUNC  M ");

                }else {
                    Log.d(Tag, "THIS IS A error are you undenstard AA  UN FUNC  M ");

                }

            }
        });


        return view;
    }
    /**
     * 获取服务端数据
     */
//    public void getPublicTimeline() throws JSONException {
//        DjangoRestClient.get("recent/?source=2&count=20&category=__all__&max_behot_time=1460214247&utm_source=toutiao&offset=0&max_create_time=1460209550&_=1460215600673",
//                null, new JsonHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                        // If the response is JSONObject instead of expected JSONArray
////                        System.out.println(response);
//                        try {
//                            JSONArray array = response.getJSONArray("data");
//
//                            for (int i = 0; i < array.length(); i++) {
//
//                                HashMap<String, Object> tempHashMap = new HashMap<String, Object>();
//                                tempHashMap.put("news_title", array.getJSONObject(i)
//                                        .getString("title"));
//                                tempHashMap.put("news_from", array.getJSONObject(i)
//                                        .getString("source"));
//                                tempHashMap.put("news_judge", array.getJSONObject(i)
//                                        .getString("comments_count") + "评论数量");
//                                tempHashMap.put("news_time", array.getJSONObject(i)
//                                        .getString("datetime"));
//
//                                arrayList.add(tempHashMap);
//                            }
//                            System.out.print(arrayList.toString());
//                            System.out.print("状态码" + statusCode);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//
//                    }
//
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
//                        // Pull out the first event on the public timeline
//                        try {
//                            JSONObject firstEvent = (JSONObject) timeline.get(0);
//
//                            String tweetText = firstEvent.getString("text");
//
//                            // Do something with the response
//
//
//                            System.out.println(tweetText);
//                        } catch (JSONException e) {
//                            //do something
//                        }
//
//                    }
//                });
//    }
    public void getPublicTimeline() throws JSONException {
        DjangoRestClient.get("/demo/test/?format=json",
                null, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        // If the response is JSONObject instead of expected JSONArray
                        System.out.println(response);
                        try {
                            JSONArray array = response.getJSONArray("data");



                            System.out.print("状态码" + statusCode);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
                        // Pull out the first event on the public timeline
                        //这是我的后台适应编码
//                        System.out.println(timeline);

                        try {
//                            JSONObject firstEvent = (JSONObject) timeline.get(0);
                            JSONArray secondEvent = (JSONArray) timeline;

//                            String tweetText = firstEvent.getString("title");

                            // Do something with the response
                            for (int j = 0; j < secondEvent.length(); j++) {
                                JSONObject firstEvent = (JSONObject) timeline.get(j);
                                HashMap<String, Object> tempHashMap = new HashMap<String, Object>();
                                //新闻标题
                                String title = firstEvent.getString("title");
                                //新闻时间
                                String description = firstEvent.getString("description");
                                //新闻来源
                                String link = firstEvent.getString("link");
                                //新闻序号
                                String linkmd5id = firstEvent.getString("linkmd5id");
                                tempHashMap.put("news_title", title);
                                tempHashMap.put("news_from", link);
                                tempHashMap.put("news_judge", linkmd5id);
                                tempHashMap.put("news_time", description);
                                arrayList.add(tempHashMap);

                            }


                            System.out.println(arrayList);

//                            System.out.println(tweetText);
                        } catch (JSONException e) {
                            //do something
                        }

                    }
                });


    }

    /**
     * getData
     */
    private ArrayList<HashMap<String, Object>> getData() {

        return arrayList;

    }
    /**
     * 捕获单击事件
     */


}

单击提示有错误:

                                                                                   at android.widget.ListView.layoutChildren(ListView.java:1562)
                                                                                   at android.widget.AbsListView$CheckForTap.run(AbsListView.java:3261)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-12 00:42:38.120 29022-29022/com.example.fiz.myapplication I/Process: Sending signal. PID: 29022 SIG: 9
阅读 3.2k
2 个回答
adapter.notifyDataSetChanged();

这个要在数据发生改变之后才调用

错误原因终于找到:当用AsyncHttpClient时,程序会自动新开一个线程,数据获取在一个线程,而adapter中的getCount又在另一个线程,两者的进度是无法把握的。结果很明显了
现将纠正后的代码奉献出
package com.example.fiz.myapplication;

/**

  • Created by Fiz on 16/3/21.

  • 和服务器进行通信
    */

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.os.Handler;
import android.widget.SimpleAdapter;
import com.example.fiz.myapplogin.DjangoRestClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

@SuppressLint("ValidFragment")
public class Home2 extends Fragment {

private String textString;
private Handler mHandler;
private static final String Tag = "MainActivity";
private ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
public Home2(String textString) {
    this.textString = textString;
}

public static Home2 newInstance(String textString) {
    Home2 mFragment = new Home2(textString);
    return mFragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.home_page, container, false);
    final ListView listView = (ListView) view.findViewById(R.id.listView);
    DjangoRestClient.get("/demo/test/?format=json",
            null, new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    // If the response is JSONObject instead of expected JSONArray
                    System.out.println(response);
                    try {
                        JSONArray array = response.getJSONArray("data");
                        System.out.print("状态码" + statusCode);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {

                    try {
                        JSONArray secondEvent = (JSONArray) timeline;
                        for (int j = 0; j < secondEvent.length(); j++) {
                            JSONObject firstEvent = (JSONObject) timeline.get(j);
                            HashMap<String, Object> tempHashMap = new HashMap<String, Object>();
                            //新闻标题
                            String title = firstEvent.getString("title");
                            //新闻时间
                            String description = firstEvent.getString("description");
                            //新闻来源
                            String link = firstEvent.getString("link");
                            //新闻序号
                            String linkmd5id = firstEvent.getString("linkmd5id");
                            tempHashMap.put("news_title", title);
                            tempHashMap.put("news_from", link);
                            tempHashMap.put("news_judge", linkmd5id);
                            tempHashMap.put("news_time", description);
                            arrayList.add(tempHashMap);
                        }
                        final SimpleAdapter adapter = new SimpleAdapter(getActivity(), getData(), R.layout.home_page_text,
                                new String[]{"news_title", "news_from", "news_judge","news_time"},
                                new int[]{R.id.news_title, R.id.news_from, R.id.news_judge,R.id.news_time});
                        listView.setAdapter(adapter);
                        System.out.println(arrayList);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

    /**
     *事件监听
     */
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (!arrayList.get(position).equals(null)) {
                Log.d(Tag, "THIS IS A JOKKE AA  UN FUNC  M ");

            } else {
                Log.d(Tag, "THIS IS A error are you undenstard AA  UN FUNC  M ");
            }
        }
    });
    return view;
}
/**
    • getData
      */

    1. ArrayList<HashMap<String, Object>> getData() {

         return arrayList;
      

      }

    }

    撰写回答
    你尚未登录,登录后可以
    • 和开发者交流问题的细节
    • 关注并接收问题和回答的更新提醒
    • 参与内容的编辑和改进,让解决方法与时俱进
    推荐问题