当没有互联网连接android时,listview中的现有项目在刷新时消失

时间:2014-11-18 05:31:31

标签: android listview android-asynctask refresh

我有一个包含自定义布局的列表视图。我正在从服务器中检索数据并在列表视图视图中显示它。

我正在使用Pull to refresh listview

提供互联网连接--->当我拉动刷新时,数据成功更新

没有互联网连接--->当我拉动刷新时,现有数据消失,使listview为空,这不是预期的

当没有可用的互联网连接时,我希望现有数据仍然可见。

HomeFragent.java

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

        View rootView = inflater.inflate(R.layout.listview_layout, container,false);
        View footer_image=inflater.inflate(R.layout.listview_image_footer, null,false);
        //footer_image.setClickable(false);


            /* get theme webservice*/

        StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy1); 


        userFunction=new UserFunctions();

            //Breaking News Section
            slide = AnimationUtils.loadAnimation(getActivity(), R.anim.slidedown);
            fadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fadeout);
            pan_breaking_new = (LinearLayout)rootView.findViewById(R.id.pan_breaking_new);
            //pan_breaking_new.setOnClickListener(this);    
            pan_breaking_new.setVisibility(8);

            btn_close= (ImageView) rootView.findViewById(R.id.btn_close);
            btn_close.setOnClickListener(this);
            img_share= (ImageView) rootView.findViewById(R.id.img_share);
            img_share.setOnClickListener(this);
            //END Breaking News Section

            //Ticker
            marque = (ScrollingTextView)rootView.findViewById(R.id.txtTicker);
            marque.setVisibility(8);
            //END ticker


            main_error = (TextView) rootView.findViewById(R.id.main_error);
            main_error.setText("Loading...");
            img_error = (ImageView) rootView.findViewById(R.id.img_error);
            img_error.setOnClickListener(this);


            progressBar1 = (ProgressBar) rootView.findViewById(R.id.progressBar1);
            progressBar1.setVisibility(8);



            //karthik
            refreshable_listView = (PullToRefreshListView) rootView.findViewById(R.id.listView);
            listView=refreshable_listView.getRefreshableView();
            listView.addFooterView(footer_image, null, false);

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

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    // TODO Auto-generated method stub

                     listView=refreshable_listView.getRefreshableView();                        

                    try {
                        getTheme();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    new GetList().execute(index_th);

                }


            });     
            newsList = new ArrayList<HashMap<String, String>>();
            mAdapter = new MyCustomAdapter(getActivity(), newsList);                            
            refreshable_listView.setAdapter(mAdapter);




            listView.setOnItemClickListener(new OnItemClickListener() {     
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {

                news_flag= (TextView) view.findViewById(R.id.flag);
                news_id = (TextView) view.findViewById(R.id.fid);
                news_live = (TextView) view.findViewById(R.id.live);
                news_title_live = (TextView) view.findViewById(R.id.title);


                //news_flag.getText().toString();
                //Log.e("-->", news_flag.getText().toString());

                //checking for click banner or neews
                if(news_flag.getText().toString().equals("normal")){

                    // Starting a new async task
                    new ViewSingleNews().execute();

                }else{

                    /*Intent intent = new Intent();
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse(All_link.IMAGE_URI_BANNER+news_flag.getText().toString()),"image/*");

                    startActivity(intent);*/
                }



            }

        });
        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {


            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

                int count = Integer.parseInt(index_temp)+6;
                System.out.println("Checking "+ listView.getLastVisiblePosition());
                System.out.println("----->Checking loadmore:"+ load_more);
                System.out.println("----->Checking actual:"+ count);

                   if (listView.getLastVisiblePosition()+1  == count) {

                       if(load_more==1){


                            index_temp = String.valueOf(Integer.parseInt(icount) + Integer.parseInt(index_temp));

                            new GetList_ontouch().execute(index_temp);
                        }
                    }
            }
        });

        //listView.addHeaderView(pan_breaking_new);
        mSeparatorsSet = new TreeSet<Integer>();
        mSeparatorsSet_alternate_layout = new TreeSet<Integer>();
        mSeparatorsSet_live_layout = new TreeSet<Integer>();

        new GetList_img_error().execute(index_th); // same as GetList(), but displays dialog 

        return rootView;

}

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();
        }

        @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) {     

            // TODO Auto-generated method stub
            mAdapter.notifyDataSetChanged();
            refreshable_listView.invalidate();
            refreshable_listView.requestLayout();
            refreshable_listView.onRefreshComplete();


            super.onPostExecute(result);


            if(error_flag==1){

                listView.setVisibility(8);
                main_error.setText("Internet Connection Error! Please check your network settings and try again");
                main_error.setVisibility(0);
                img_error.setVisibility(0);

            }else{

                listView.setVisibility(0);
                main_error.setText("");
                main_error.setVisibility(8);
                img_error.setVisibility(8);
                int currentPosition = listView.getFirstVisiblePosition();

                mAdapter = new MyCustomAdapter(getActivity(), newsList);
                //testing
                listView.setAdapter(mAdapter);
                refreshable_listView.setAdapter(mAdapter);
                 // Setting new scroll position
                listView.setSelection(currentPosition);
                mAdapter.notifyDataSetChanged();
            }

            SharedPreferences sharedPrefs = getActivity().getSharedPreferences(All_link.MyPREFERENCES,
                    Context.MODE_PRIVATE);
            sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

            //For Breaking News Setting
            if (sharedPrefs.getInt("prefswtch4", 1) == 1) {

                if (All_link.GLOBAL_BREAKING_FLAG == 0) {

                    new getBreakingNews().execute();

                }

            } 

            //For Location Setting
            if (sharedPrefs.getInt("prefswtch1", 1) == 1) {



            } else {



            }

            //For Ticker Setting
            if (sharedPrefs.getInt("prefswtch2", 1) == 1) {

                new getTicker().execute();

            } else {

                marque.setVisibility(8);

            }




        }
        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            refreshable_listView.onRefreshComplete();
        }

    }

1 个答案:

答案 0 :(得分:1)

最后我解决了这个问题。

我刚刚在SharedPreference中保存了字符串jsonStr,并创建了单独的

class GetList_refresh extends AsyncTask<String, String, Void>

并且当没有网络可用时调用new GetList_refresh().execute(index_th,jsonStr);

它按预期完美运作......