paul590
paul590

Reputation: 1435

ListViews duplicating on Tabs after selecting last Tab

Hello I am running in a weird issue. My listview on my tabs loads fine. The issue that I encounter is when I scroll to the last Tab and then go back to the other tabs, their list have duplicated. Any ideas what could cause this to happen? Thank you in advance.

Java:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_tab, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(this);

        newslist = (ListView) view.findViewById(R.id.displaynews);

        newsName = getArguments().getString("newsName");
        loadnews(newsName);
        if (adapter == null) {
            adapter = new CustomAdapter(getActivity(), listnews);
            newslist.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }else{
            newslist.setAdapter(adapter);
        }


        return view;

    }

Loadnews Method:

public LinkedList<News> loadTopNews(){
     String result = pullfromDB();
try{
            jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
     );


                        news = new News(json_data.getString("id"), title.toUpperCase(), json_data.getString("date"));
                        listnews.add(news);

                    }
                }
            }
        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return listnews;
    }
}

Upvotes: 0

Views: 61

Answers (2)

Vickyexpert
Vickyexpert

Reputation: 3171

Check Answer and replace in your code below methid,

  public LinkedList<News> loadTopNews()
  {
       listnews = new ArrayList()<>;

       String result = pullfromDB();

       try
       {
            jArray = new JSONArray(result);

            for(int i=0;i<jArray.length();i++)
            {
               JSONObject json_data = jArray.getJSONObject(i);

               news = new News(json_data.getString("id"), title.toUpperCase(), json_data.getString("date"));
               listnews.add(news);
            }
       }catch(JSONException e){
           Log.e("log_tag", "Error parsing data " + e.toString());
       }

       return listnews;
  }

Upvotes: 1

Manish Jain
Manish Jain

Reputation: 2339

onCreateView method call everytime in the fragment.

The below line add the data in the list everytime, so you get the duplicate data.

loadnews(newsName);

Upvotes: 1

Related Questions