android - 刷新android时listview数据消失

标签 android listview android-asynctask refresh

我成功地使用已经可用的库实现了 Pull to refresh listview。现在问题是刷新时,listview 中已经显示的数据消失了(页面空白),刷新完成后数据与更新后的数据一起显示,这不是预期的结果

public class HomeFragment extends Fragment implements OnClickListener{
private ListView listView;
PullToRefreshListView refreshable_listView;
private MyCustomAdapter mAdapter;
ArrayList<HashMap<String, String>> newsList;
String index_th="0";

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.listview_layout, container,false);

            //karthik
            refreshable_listView = (PullToRefreshListView) rootView.findViewById(R.id.listView);

            refreshable_listView.setOnRefreshListener(new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    // TODO Auto-generated method stub                                                                  
                    new GetList().execute(index_th);
                }


            });

            listView=refreshable_listView.getRefreshableView();
}
private class GetList extends AsyncTask<String, Void, Void> {
        Dialog dialog = new Dialog(getActivity());
        String jsonStr;
        ArrayList<HashMap<String, String>> Local_newsList;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Local_newsList=new ArrayList<HashMap<String,String>>();



            // Showing progress dialog
            /*dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout._wait_dialog);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            dialog.show();*/

        }

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

            if (NetworkCheck.isNetworkAvailable(getActivity()) == true) {

                //Log.d("index count for array", params[0]);
                if(Integer.parseInt(params[0])==0){
                    //Log.d("index count for array","Rweached");
                    newsList = new ArrayList<HashMap<String, String>>();
                }


                // Creating service handler class instance
                ServiceHandler sh = new ServiceHandler();

                // Making a request to url and getting response
                jsonStr = sh.makeServiceCall(All_link.HOME_DATA_URL + "/"+params[0]+"/"+ icount,
                        ServiceHandler.GET);

                Log.d("Response: ", "> " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node
                        news = jsonObj.getJSONArray(All_link.TAG_NEWS);


                        err = jsonObj.getString(All_link.TAG_ERROR);
                        String more = jsonObj.getString(All_link.TAG_MORE);

                        Log.e("------>Error",String.valueOf(err));
                        Log.e("------>More",String.valueOf(more));
                        if(more.equals("0")){

                            load_more = 0;

                        }else{

                            load_more = 1;
                        }

                        // looping through All Contacts
                        for (int i = 0; i < news.length(); i++) {

                            //karthik



                            JSONObject segments_list = news.getJSONObject(i);

                            for (int plates_count = 0; plates_count < segments_list
                                    .length(); plates_count++) {


                                String plates = "";
                                if (plates_count == 3) {
                                    plates = String.valueOf("banner_image");

                                    JSONObject segments_plates = segments_list
                                            .getJSONObject(plates);

                                    //String flag = "banner_image";
                                    String id = segments_plates
                                            .getString(All_link.TAG_BANNER_ID);
                                    String banner_no = segments_plates
                                            .getString(All_link.TAG_BANNER_NO);

                                    String banner_image;

                                    if(segments_plates.getString(All_link.TAG_BANNER_THUMB_URL)==""){

                                        banner_image = All_link.TAG_NO_IMAGE;
                                    }else{

                                        banner_image = segments_plates.getString(All_link.TAG_BANNER_THUMB_URL);
                                    }

                                    String banner_status = segments_plates
                                            .getString(All_link.TAG_BANNER_STATUS);


                                    // tmp hashmap for single news
                                    HashMap<String, String> news_hashmap = new HashMap<String, String>();

                                    // adding each child node to HashMap key =>
                                    // value
                                    news_hashmap.put(All_link.TAG_BANNER_ID, id);
                                    news_hashmap.put(All_link.TAG_BANNER_NO,
                                            banner_no);
                                    news_hashmap.put(All_link.TAG_BANNER_THUMB_URL,
                                            banner_image);
                                    news_hashmap.put(All_link.TAG_BANNER_STATUS,
                                            banner_status);
                                    /*news_hashmap
                                            .put(All_link.TAG_BANNER_FLAG, flag);*/

                                    // adding contact to contact list



                                    newsList.add(news_hashmap);


                                    //karthik newsList

                                    //Local_newsList.add(news_hashmap);


                                    addSeparatorItem();
                                } else {
                                    plates = String.valueOf(plates_count + 1);

                                    JSONObject segments_plates = segments_list
                                            .getJSONObject(plates);

                                    if(segments_plates.getString(All_link.TAG_NEWS_TYPE).equals("2")){

                                        //type_of_news = segments_plates.getString(All_link.TAG_NEWS_TYPE);
                                        addSeparatorItem_for_live();
                                    }                                   

                                    String id = segments_plates.getString(All_link.TAG_ID);
                                    String news_title = segments_plates.getString(All_link.TAG_NEWS_TITLE);
                                    String news_desc = segments_plates.getString(All_link.TAG_DESC);
                                    String segment = segments_plates.getString(All_link.TAG_SEGMENT);
                                    String plate = segments_plates.getString(All_link.TAG_PLATE);

                                    String img ="";
                                    if(segments_plates.getString(All_link.TAG_THUMB_URL).equals("")){

                                        img = All_link.TAG_NO_IMAGE;

                                    }else{

                                        img = segments_plates.getString(All_link.TAG_THUMB_URL);
                                    }


                                    HashMap<String, String> news_hashmap = new HashMap<String, String>();

                                    // adding each child node to HashMap key =>
                                    // value
                                    news_hashmap.put(All_link.TAG_ID, id);
                                    news_hashmap.put(All_link.TAG_NEWS_TITLE, news_title);
                                    news_hashmap.put(All_link.TAG_DESC, news_desc);
                                    news_hashmap.put(All_link.TAG_SEGMENT, segment);
                                    news_hashmap.put(All_link.TAG_PLATE, plate);
                                    news_hashmap.put(All_link.TAG_THUMB_URL, img);
                                    //news_hashmap.put(All_link.TAG_BANNER_FLAG, flag);
                                    // adding contact to contact list

                                    newsList.add(news_hashmap);



                                    //karthik newsList

                                    //Local_newsList.add(news_hashmap);

                                    int val = 0;
                                    int val2 = 1;
                                    val = (Integer.parseInt(segment)%2)==0 ? val:val2;

                                    if((Integer.parseInt(segment)%2)!=0){
                                        Log.e("--->CHECKING ODD EVEN", String.valueOf(val));
                                        addSeparatorItem();
                                        addSeparatorItem_for_alternate();   
                                    }
                                }
                            }

                        }
                    } catch (JSONException e) {
                        Local_newsList=null;
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } else {
                Log.e("Network Error", "Internet Connection Error");
                error_flag = 1;
                // error = "Internet Connection Error";

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    mAdapter = new MyCustomAdapter(getActivity(), newsList);                            

                    mAdapter.notifyDataSetChanged();
                    refreshable_listView.setAdapter(mAdapter);
                         refreshable_listView.onRefreshComplete();


                }
            });

            super.onPostExecute(result);            
}

MyCustomAdapter.java

private class MyCustomAdapter extends BaseAdapter {

        private Activity activity;
        Boolean result;
        private final LayoutInflater inflater = null;
        public ImageLoader imageLoader;

        private static final int TYPE_ITEM = 0;
        private static final int TYPE_SEPARATOR = 1;
        private static final int TYPE_SEPARATOR_ALTERNATE = 2;
        private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 3;
        private int live_type = 0;


        private LayoutInflater mInflater;

        public MyCustomAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
            mInflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            activity = a;
            newsList=d;
            imageLoader = new ImageLoader(activity.getApplicationContext());
        }

        @Override
        public int getItemViewType(int position) {

            int separtorValue;
            int pos = mSeparatorsSet.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
            live_type = mSeparatorsSet_live_layout.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
            if(pos==1){
                //Log.e("--->if called- position->", String.valueOf(position));
                if(mSeparatorsSet_alternate_layout.contains(position)){

                    //Log.e("--->if called-->", String.valueOf(position));
                    separtorValue = 2;
                }else{

                    separtorValue = 1;  
                }


            }else{

                separtorValue = 0;
            }


            return separtorValue;
        }


        @Override
        public int getViewTypeCount() {
            Log.e("--->TYPE_MAX_COUNT called-->", String.valueOf(TYPE_MAX_COUNT));
            return TYPE_MAX_COUNT;
        }

        @Override
        public int getCount() {
            return newsList.size();
        }

        @Override
        public HashMap<String, String> getItem(int position) {
            return newsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            NewsViewHolder holder = null;
            int type = getItemViewType(position);

            Log.e("--->SHISHIR-->", String.valueOf(live_type));

            /*System.out.println("getView " + position + " " + convertView
                    + " type = " + type);
**/
            //Log.e("--->SHISHIR-->", String.valueOf(position) + " -->live"+String.valueOf(mSeparatorsSet_live_layout.first()));



            if (convertView == null) {
                holder = new NewsViewHolder();

                 //Log.e("--itempostion", String.valueOf(getItem(type)));

                switch (type) {
                case TYPE_ITEM:




                    if (CURRENT_THEME==1) {
                        convertView = mInflater.inflate(
                                R.layout.theme_one_row_small, null);
                    }

                    else{
                        convertView = mInflater.inflate(
                                R.layout.theme_one_row_small_new, null);
                    }




                    holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
                    holder.id = (TextView) convertView.findViewById(R.id.fid);
                    holder.live = (TextView) convertView.findViewById(R.id.live);
                    holder.flag = (TextView) convertView.findViewById(R.id.flag);
                    holder.name = (TextView) convertView
                            .findViewById(R.id.title);

                    holder.img = (ImageView) convertView
                            .findViewById(R.id.list_image);

                    imageLoader
                            .DisplayImage(
                                    com.rb.library.All_link.IMAGE_URI_BANNER
                                            + newsList.get(position).get(
                                                    All_link.TAG_THUMB_URL),
                                    holder.img);

                    break;
                case TYPE_SEPARATOR_ALTERNATE:





                    if (CURRENT_THEME==1) {
                        convertView = mInflater
                                .inflate(R.layout.theme_one_row_big, null);
                    }

                    else{
                        convertView = mInflater
                                .inflate(R.layout.theme_one_row_big_new, null);
                    }



                    holder.flag = (TextView) convertView.findViewById(R.id.flag);

                    holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
                    holder.id = (TextView) convertView.findViewById(R.id.fid);
                    holder.live = (TextView) convertView.findViewById(R.id.live);
                    holder.name = (TextView) convertView
                            .findViewById(R.id.title);
                    holder.img = (ImageView) convertView
                            .findViewById(R.id.list_image);


                    break;
                case TYPE_SEPARATOR:
                    convertView = mInflater
                            .inflate(R.layout.theme_banner, null);
                    holder.flag = (TextView) convertView.findViewById(R.id.flag);
                    holder.id = (TextView) convertView.findViewById(R.id.fid);
                    holder.name = (TextView) convertView
                            .findViewById(R.id.title);
                    holder.img = (ImageView) convertView
                            .findViewById(R.id.list_image);

                    break;


                }


                convertView.setTag(holder);
            } else {
                holder = (NewsViewHolder) convertView.getTag();
            }

            switch (type) {
            case TYPE_ITEM:

                if(live_type == 1){

                    holder.img_flag.setVisibility(0);
                    holder.live.setText("live");

                }else{

                    holder.live.setText("not_live");
                    holder.img_flag.setVisibility(8);
                }
                imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
                        holder.img);
                holder.id.setText(String.valueOf(newsList.get(position).get(
                        All_link.TAG_ID)));
                holder.flag.setText("normal");

                break;
            case TYPE_SEPARATOR_ALTERNATE:

                if(live_type == 1){

                    holder.img_flag.setVisibility(0);
                    holder.live.setText("live");
                    //Log.e("--itempostion Live", "live");
                }else{

                    holder.live.setText("not_live");
                    holder.img_flag.setVisibility(8);
                }

                imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
                        holder.img);
                holder.id.setText(String.valueOf(newsList.get(position).get(
                        All_link.TAG_ID)));
                holder.flag.setText("normal");

                Log.e("karthik", "karthik "+com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL));

                break;
            case TYPE_SEPARATOR:
                Log.e("--banner Images", com.rb.library.All_link.IMAGE_URI_BANNER
                        + newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
                imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI_BANNER
                        + newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL),
                        holder.img);
                holder.id.setText(String.valueOf(newsList.get(position).get(
                        All_link.TAG_BANNER_ID)));
                holder.flag.setText(newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
                break;
            }





            holder.name.setText(String.valueOf(newsList.get(position).get(All_link.TAG_NEWS_TITLE)));

            return convertView;
        }

    }

最佳答案

我的猜测是因为你每次在 onPostExecutepull to refresh 时调用 setAdapter :

mAdapter = new MyCustomAdapter(getActivity(), newsList);                            
mAdapter.notifyDataSetChanged();
refreshable_listView.setAdapter(mAdapter);
refreshable_listView.onRefreshComplete();

尝试移动:

mAdapter = new MyCustomAdapter(getActivity(), newsList);                            
refreshable_listView.setAdapter(mAdapter);

到您的 onCreateView 因为您只需要初始化和设置适配器一次

您只需要在 onPostExecute 中调用它们,因为您在 onBackground 中调用了 newsList.add :

mAdapter.notifyDataSetChanged();
refreshable_listView.onRefreshComplete();

上面的代码只会更改您的 ListView 上的数据,而不会重新初始化任何内容。

关于android - 刷新android时listview数据消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26944332/

相关文章:

android - 在应用程序的生命周期中,伴随对象是否保留在内存中

javascript - 使用 JQuery mobile 创建 ListView 无法正常工作 II

android - 多个图像进度条加载就像在 Whats App 中一样

android - 关闭 Activity 时如何停止 Activity 的线程和套接字

android - 不同类型的 fragment 管理器

android - 如何使用 ViewModel 存储位图列表以便在生命周期变化中生存?

wordpress - WooCommerce ListView

java - AsyncTask 仅适用于调试?

java - 当AsyncTasks满了会发生什么?

android - 什么可能导致此 SQLite CursorWindowAllocationException?