0

I am unable to refresh my ListView in ListFragment with new data. Instead the new data is added to the previous.

The time period is from 6AM to 5PM for each entity. Then new data is appended to the list restarting at 6AM for another entity. The data for the first entity should be cleaned before the second is added to the ListView.

Here is the code:

public class FragmentStatePagerSupport extends FragmentActivity {

   static final int NUM_ITEMS = 4; //control number of fragments
   MyAdapter mAdapter;
   ViewPager mPager;


   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.fragment_main);

       mAdapter = new MyAdapter(getSupportFragmentManager());
       mPager = (ViewPager)findViewById(R.id.pager);
       mPager.setAdapter(null);
       mPager.setAdapter(mAdapter);
   }

   //===============================================================================================
   public static class MyAdapter extends FragmentStatePagerAdapter {

       public MyAdapter(FragmentManager fm) {
           super(fm);
       }

       @Override
       public int getCount() {
           return NUM_ITEMS;
       }

       @Override
       public Fragment getItem(int position) {
           fragNumber = position;
           return ArrayListFragment.newInstance(position);
       }
   }

   //===============================================================================================
   public static class ArrayListFragment extends ListFragment  {
       Integer mNum;
       String FORMAT_LINE = "%s%7s%7s%10s%16s";

       static ArrayListFragment newInstance(int num) {
           ArrayListFragment f = new ArrayListFragment();
           Bundle args = new Bundle();
           args.putInt("num", num);
           f.setArguments(args);
           return f;
       }

       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           mNum = getArguments() != null ? getArguments().getInt("num") : 1;
       }

       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                Bundle savedInstanceState) {
           View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
           View tv = v.findViewById(R.id.text);
           View tvd = v.findViewById(R.id.tv_description);

           String title = "";
           switch (mNum){
               case 0:title = MyGlobals.getInstance().getToday();break;
               case 1:title = MyGlobals.getInstance().getTomorrow();break;
               case 2:title = MyGlobals.getInstance().getDayAfter();break;
               case 3:title = MyGlobals.getInstance().getDayDayAfter();break;
           }

           ((TextView) tv).setText(MyGlobals.getInstance().getName() + " on " + title);
           ((TextView) tvd).setText(String.format(FORMAT_LINE, "time", "temp", "rain", "wind", "weather"));
           return v;

       }


       @Override
       public void onActivityCreated(Bundle savedInstanceState) {
           super.onActivityCreated(savedInstanceState);
           ArrayList<Data> row = Data.getRows(mNum);
           ListViewAdapter adapter = new ListViewAdapter(getActivity(), row);
           getListView().setAdapter(null);
           getListView().setAdapter(adapter);
       }


       @Override
       public void onListItemClick(ListView l, View v, int position, long id) {
           v.setBackgroundColor(getResources().getColor(R.color.blue));

       }
   }

   //==============================================================================================
   public static class ListViewAdapter extends ArrayAdapter<Data> {

       public static class ViewHolder{
           TextView time;
           TextView temp;
           TextView rain;
           TextView wind_speed;
           TextView weather;
       }

       public ListViewAdapter(Context context, ArrayList<Data> list) {super(context, R.layout.text_listview, list); }

           @Override
           public View getView(int position, View convertView, ViewGroup parent) {
               Data data = getItem(position);
               ViewHolder holder;
               if(convertView == null){
                   holder=new ViewHolder();
                   LayoutInflater inflater = LayoutInflater.from(getContext());
                   convertView=inflater.inflate(R.layout.text_listview,parent,false);
                   holder.time=(TextView) convertView.findViewById(R.id.time);
                   holder.temp=(TextView) convertView.findViewById(R.id.temp);
                   holder.rain=(TextView) convertView.findViewById(R.id.rain);
                   holder.wind_speed=(TextView) convertView.findViewById(R.id.wind);
                   holder.weather=(TextView) convertView.findViewById(R.id.weather);
                   convertView.setTag(holder);
               }else{
                   holder=(ViewHolder) convertView.getTag();
               }
               holder.time.setText(data.time);
               holder.temp.setText(data.temp);
               holder.rain.setText(data.rain);
               holder.wind_speed.setText(data.wind_speed);
               holder.weather.setText(data.weather);
               return convertView;
           }
   }
}

This last piece populates the ListView. The calls adapter.clear() and adapter.notifyDataSetChanged() does not resolve the problem.

There is a similar question from 3 years ago How update ListView in ListFragment from FragmentActivity? still without accepted response despite the 6836 views.

Thanks a Lot.

The GetRows(mNum) piece as requested:

public class Data {
  public String time;
  public String temp;
  public String rain;
  public String wind_speed;
  public String weather;

  public Data(String time, String temp, String rain, String wind_speed, String weather) {
    this.time = time;
    this.temp = temp;
    this.rain = rain;
    this.wind_speed = wind_speed;
    this.weather = weather;

  }

  public static ArrayList<Data> getRows(int fragNumber) {

    int mNum = fragNumber;
    int size;
    String myList[] = null;

    ArrayList<Data> list = new ArrayList<Data>();

    switch (mNum) {
        case 0://Today
            size = MyGlobals.getInstance().getToday("time").size();
            myList = new String[size];
            for (int i = 0; i < size; i++) {
                String time = (String) MyGlobals.getInstance().getToday("time").get(i);
                String temp = (String) MyGlobals.getInstance().getToday("temperature").get(i);
                String wind_speed = (String) MyGlobals.getInstance().getToday("wind_speed").get(i);
                String pop = (String) MyGlobals.getInstance().getToday("pop").get(i);
                //String wind_gust = (String) MyGlobals.getInstance().getToday("wind_gust").get(i); //when null breaks code
                String weather = (String) MyGlobals.getInstance().getToday("weather").get(i);

                if (time.length() == 4) time = "0" + time;
                if (wind_speed.length() == 1) wind_speed = "0" + wind_speed;
                if (pop.length() == 1) pop = "0" + pop;
                list.add(new Data(time,temp,pop,wind_speed,weather));

            }
            return list;
        case 1://Tomorrow
            ...snip... same as above with pertinent variables,...
        case 2://DayAfter
            ...snip...
        case 3://DayDayAfter
            ...snip....
        case 4:// is an error
            Log.d("***error***", "list got to case 5");
    }
     return list;
   }
}
Community
  • 1
  • 1

2 Answers2

0

It's because everytime you set an Adapter, it will really be added., remove all its data first before setting again so it will be like

mPager.setAdapter(null);

before doing

mPager.setAdapter(mAdapter);
Sheychan
  • 2,415
  • 14
  • 32
0

Try this;

  • Before adding new list of Data to the existing list, use list.clear();
  • Add new Data to the list and you should have only newly added data in the list..
  • pass the list to your adapter class.
  • Notify adapter of the new data i.e. adapter.notifyDataSetChanged()

    You are returning list twice in your getRows()

  • remove the "return list" before the case structure

    public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Clear old list here before adding new one. if (list! = null) { list.clear(); } // Add New list

    list = Data.getRows(mNum); ListViewAdapter adapter = new ListViewAdapter(getActivity(), list); getListView().setAdapter(adapter); adapter.notifyDataSetChange(); }

Want2bExpert
  • 527
  • 4
  • 11
  • I think I tried that before and it didn't work since the list is newly created in GetRows(). Nonetheless I'd do as you say and report. Thanks for the comment. – Walter Roncada Aug 29 '15 at 18:58
  • Yep, it doesn't work either. In onActivityCreated() if I clear the list after getListView().setAdapter(adapter); the lIstView comes out blank. I can't clear the list before setting the adapter as well for the result is the same. – Walter Roncada Aug 29 '15 at 19:15
  • The list doesn't exist before Add new list....so I can't use list.clear(). As per previous comment, if I list.clear() after the adpter has been set then the listview is blank... – Walter Roncada Aug 29 '15 at 19:24
  • You're returning list twice in your getRows method. Check my edited answer – Want2bExpert Aug 29 '15 at 20:22
  • The second return list is required or Error:(163, 5) error: missing return statement. It would be null if the list was not built in the switch() statement. At any rate I replaced the last "return list;" with "return null;" and the problem persists. Also, it is not possible to set if (list! = null) { list.clear(); } as you suggested because "list" at this point is still undefined. – Walter Roncada Aug 29 '15 at 21:46
  • 1
    It appears I have an internal consistency flaw in my code coming from switching activities. This can't be helped based on the code snippets provided. I am trying to isolate the problem and will report back if I can correct it. – Walter Roncada Aug 29 '15 at 22:10
  • 1
    I found the problem to be in: case 0:title = MyGlobals.getInstance().getToday();break; case 1:title = MyGlobals.getInstance().getTomorrow();break; whereby another activity would update the data but not clear the previous ArrayList<> so the data was accumulating and not replacing. Adding a new method: MyGlobals.getInstance().clear(); resolved the issue. Even though the issue could not be resolved through your recommendations they did put me in the right track. Therefore I have accepted your contribution. Thanks. – Walter Roncada Aug 30 '15 at 20:53