Android,Fragment使用AsyncHttpClient数据不显示

先贴代码:
NewsFragment.java

public class NewsFragment extends Fragment {
    private final static String TAG = "NewsFragment";
    Activity activity;
    ArrayList<NewsEntity> newsList = new ArrayList<NewsEntity>();
    HeadListView mListView;
    NewsAdapter mAdapter;
    int channel_id;
    ImageView detail_loading;
    public final static int SET_NEWSLIST = 0;

    /** 此方法意思为fragment是否可见 ,可见时候加载数据 */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {   //onCreateView之前调用的
        if (isVisibleToUser) {
            System.out.println("isVisibleToUser");
            System.out.println(channel_id);
            if (channel_id == 0) {
                channel_id = 1;
            }
            initData();
            //fragment可见时加载数据
            if(newsList !=null && newsList.size() !=0){
                System.out.println("newList not null");
                handler.obtainMessage(SET_NEWSLIST).sendToTarget();
            }else{
                System.out.println("newList null");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.obtainMessage(SET_NEWSLIST).sendToTarget();
                    }
                }).start();
            }
        }else{
            System.out.println("isNotVisibleToUser");
            //fragment不可见时不执行操作
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

//  OnPageChangeListener

    @Override
    public void onAttach(Activity activity) {
        System.out.println("news_frag_onAttach");
        this.activity = activity;
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        System.out.println("news_frag_onCreate");
        Bundle args = getArguments();       //传值
//      text = args != null ? args.getString("text") : "";
        channel_id = args != null ? args.getInt("id", 0) : 0;
        System.out.println("NewsFragment_channel_id:"+channel_id);
        if (getUserVisibleHint()) {
            System.out.println("onCreate_getUserVisibleHint");
        }

        super.onCreate(savedInstanceState);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        System.out.println("news_frag_onCreateView");
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.news_fragment, null);
        mListView = (HeadListView) view.findViewById(R.id.mListView);
        detail_loading = (ImageView)view.findViewById(R.id.detail_loading);
        return view;
    }

    private void initData() {
        //newsList.clear();
        newsList = Constants2.getNewsList(channel_id);
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            System.out.println("handler:"+msg.what);
            switch (msg.what) {
            case SET_NEWSLIST:
                detail_loading.setVisibility(View.GONE);
                if(mAdapter == null){
                    mAdapter = new NewsAdapter(activity, newsList);
                    //判断是不是城市的频道
                    if(channel_id == Constants2.CHANNEL_CITY){
                        //是城市频道
                        mAdapter.setCityChannel(true);
                        initCityChannel();
                    }
                }
                mListView.setAdapter(mAdapter);
                mListView.setOnScrollListener(mAdapter);
                mListView.setPinnedHeaderView(LayoutInflater.from(activity).inflate(R.layout.list_item_section, mListView, false));
                mListView.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        Intent intent = new Intent(activity, DetailsActivity.class);
                        if(channel_id == Constants2.CHANNEL_CITY){
                            if(position != 0){
                                intent.putExtra("news", mAdapter.getItem(position - 1));
                                startActivity(intent);
                                activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                            }
                        }else{
                            intent.putExtra("news", mAdapter.getItem(position));
                            startActivity(intent);
                            activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                        }
                    }
                });
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
    };

    /* 初始化选择城市的header*/
    @SuppressLint("InflateParams")
    public void initCityChannel() {
        View headview = LayoutInflater.from(activity).inflate(R.layout.city_category_list_tip, null);
        TextView chose_city_tip = (TextView) headview.findViewById(R.id.chose_city_tip);
        chose_city_tip.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, CityListActivity.class);
                startActivity(intent);
            }
        });
        mListView.addHeaderView(headview);
    }

    /* 摧毁视图 */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d("onDestroyView", "channel_id = " + channel_id);
        mAdapter = null;
    }
    /* 摧毁该Fragment,一般是FragmentActivity 被摧毁的时候伴随着摧毁 */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "channel_id = " + channel_id);
    }
}

Contants2.java

 public class Constants2 {
    public static final String GET_NEWS_URL = AppApplication.NEWS_URL+"/getNewsJSON.php";
    public static final String GET_Comment_URL = AppApplication.NEWS_URL+"/commentlist.php";
    static ArrayList<NewsEntity> newsList = new ArrayList<NewsEntity>();
    static ArrayList<CommentEntity> commentList = new ArrayList<CommentEntity>();
    static JSONArray jsonArray;
    static JSONArray commentJsonArray;

    /*
     * 获取新闻列表
     */
    public static ArrayList<NewsEntity> getNewsList(int channel_id) {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.add("channel_id", String.valueOf(channel_id));
        System.out.println("Constants2_channel_id:"+String.valueOf(channel_id));
        client.post(GET_NEWS_URL, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int i, Header[] handler, byte[] bytes) {
                String response = new String(bytes);
                Log.e("debug","response:"+response);
                try {
                    jsonArray = new JSONArray(response);
                } catch (JSONException e) {
                    System.err.println("newslist_jsonArray_error");
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                System.out.println("数据错误!!");
            }
        });


        if (jsonArray != null) {
            System.out.println("/////////////////////////");
            System.out.println(jsonArray.length());
            newsList.clear();
            for(int i =0 ; i < jsonArray.length() ; i++){
                try {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    NewsEntity news = new NewsEntity();
                    news.setId(i);
                    news.setNewsId(obj.getString("newsId"));
                    news.setCollectStatus(false);
                    news.setCommentNum(i + 10);
                    news.setInterestedStatus(true);
                    news.setLikeStatus(true);
                    news.setReadStatus(false);
                    news.setNewsCategory("推荐");
                    news.setNewsCategoryId(1);
                    news.setSource_url("");
                    news.setTitle(obj.getString("title"));
                    List<String> url_list = new ArrayList<String>();
                    news.setPicOne(obj.getString("pic_url"));
                    url_list.add(obj.getString("pic_url"));
                    news.setPicList(url_list);
                    news.setReporter(obj.getString("reporter"));
                    news.setPublishTime(obj.getString("time"));
                    news.setReadStatus(false);
                    news.setSource("手机腾讯网");
                    news.setContent(obj.getString("content"));
                    news.setSummary("腾讯数码讯(编译:Gin)谷歌眼镜可能是目前最酷的可穿戴数码设备,你可以戴着它去任何地方(只要法律法规允许或是没有引起众怒),作为手机的第二块“增强现实显示屏”来使用。另外,虽然它仍未正式销售,但谷歌近日在美国市场举行了仅限一天的开放购买活动,价格则为1500美元(约合人民币9330元),虽然仍十分昂贵,但至少可以满足一些尝鲜者的需求,也预示着谷歌眼镜的公开大规模销售离我们越来越近了。");
                    news.setMark(i);
                    news.setIsLarge(false);
                    if(i == 2){
                        news.setComment("评论部分,说的非常好。");
                    }
//                  news.setPublishTime(Long.valueOf(obj.getString("time")));
                    if(i <= 2){
                        news.setPublishTime(DateTools.getTime());
                    }else if(i >2 && i <= 5){
                        news.setPublishTime(String.valueOf(Long.valueOf(DateTools.getTime()) - 86400));
                    }else{
                        news.setPublishTime(String.valueOf(Long.valueOf(DateTools.getTime()) - 86400 * 2));
                    }
                    newsList.add(news);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return newsList;
    }

}

流程是这样:
当前fragment可视时通过initData()加载数据,就是调用Constants2的getNewsList(channel_id) 方法,_该方法执行异步任务返回一个newsList,现在的问题是首次加载的时候数据显示,请问有什么解决方法?

4个回答

要能有数据就奇怪了,使用了多线程,不在网络线程执行完成后初始化数据,怎么跟主线程同步起来

shenshucong520
glustful 回复reqtavdfsg: 把你初始化newlist的代码扔在网络请求成功方法onsuccess里执行,再notify
接近 4 年之前 回复
reqtavdfsg
reqtavdfsg 这个问题纠结了几天,网络线程是最后才执行完成,有什么方法可以解决?我调用adapter.notifyDataSetChanged()刷新页面也没效果。
接近 4 年之前 回复

client.post(GET_NEWS_URL, params, new AsyncHttpResponseHandler()
这个是异步的,所 以你直接返回的肯定是空的值;
你需要在 success中处理把得到的值,直接给newsList, 再进行adapter.notifyDataSetChanged()刷新就可以了;

mAdapter = null; 这个最好去掉,不需要,还有可能造成异常;

reqtavdfsg
reqtavdfsg 在 success中处理把得到的值,直接给newsList,但是它最后return的newsList还是不是success中的newsList,有什么方法可以让return的list等于success中处理的newsList?
接近 4 年之前 回复

我也好想知道异步处理结束后,怎么知道他结束

试试用OKHttp或者Volley吧

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问