Update ListFragment after asynctask

2019-06-01 04:45发布

问题:

I have two listfragment and one fragment in my application. I show you first fragment.

The application starts, Asynctask retrieves data and put them in arrayNews. I think the problem is the update of listview or adapter in listfragment that does not refresh.

If I change the phone's orientation => listfragment (+ listview) appears correctly. If I go to fragment 3 (fragment in 2 and 3 in memory), then come back on fragment 1 => it works correctly.

Sorry for my english ^^

public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    public static ArrayList<Data> arrayNews = new ArrayList<Data>();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<Fragment> listeFragments = new Vector<Fragment>();
        listeFragments.add(Fragment.instantiate(this, ActualiteFragment.class.getName()));
        listeFragments.add(Fragment.instantiate(this, DossierFragment.class.getName()));
        listeFragments.add(Fragment.instantiate(this, ForumFragment.class.getName()));
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), listeFragments);

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
        {
            @Override
            public void onPageSelected(int position)
            {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
        {
            actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
        }

        if (arrayDossier.size() == 0 && arrayDossier.size() == 0)
        {
            chargement_donnees();
        }       
    }

    public void chargement_donnees()
    {
        AsyncTaskChargement chargNews = new AsyncTaskChargement();
        chargNews.execute();
    }

    public class AsyncTaskChargement extends AsyncTask<Void, Integer, Void>
    {
        private ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            dialog.setMessage("Chargement des données ...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
            arrayNews = ContainerData_news.getFeeds(); 
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            if (this.dialog.isShowing())
            {
                this.dialog.dismiss();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.menu_refresh:
            chargement_donnees();
            return true;
        default:
            return false;
        }
    }

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
    {
    }

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
    {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
    {
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter
    {
        List<Fragment> listeFragments;

        public SectionsPagerAdapter(FragmentManager fm, List<Fragment> listeFragments)
        {
            super(fm);
            this.listeFragments = listeFragments;
        }

        @Override
        public Fragment getItem(int position)
        {
            return listeFragments.get(position);
        }

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

        @Override
        public CharSequence getPageTitle(int position)
        {
            switch (position)
            {
            case 0:
                return getString(R.string.title_section1).toUpperCase();
            case 1:
                return getString(R.string.title_section2).toUpperCase();
            case 2:
                return getString(R.string.title_section3).toUpperCase();
            }
            return null;
        }
    }

    public static class ActualiteFragment extends ListFragment
    {       

        public ActualiteFragment()
        {
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState)
        {
            super.onActivityCreated(savedInstanceState);
            setListAdapter(new AdapterListe(getActivity(), arrayNews));
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {           
            return inflater.inflate(R.layout.listfragment, container, false);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id)
        {
            ...
        }
    }
}

回答1:

I found an easy way to update such list Steps would be.: 1. declare onCreateView in ListFragment

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.TheLayoutContainingAListView, container, false);
        return view;        
    }

TheLayoutContainingAListView.xml should contain only a listview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
        <ListView
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
        </ListView>
</LinearLayout>

The android:id must be "@android:id/list" . however you may try other things.. I didn't.. 2. In onPostExecute of your AsyncTask (Asynctask should be in MainActivity), do everything that you want to do.. i.e. declare an adapter, and setAdapter

protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            lv = (ListView) findViewById(android.R.id.list);
            CustomAdapter adapt = new CustomAdapter(MainActivity.this,
                    android.R.id.list, fetch); //You can use ArrayAdapter.. i wanted a custom one
            lv.setAdapter(adapt);
            showFragment(YOUR Fragment, false);

            super.onPostExecute(result);
        }

showFragment is just a function i used to show a particular fragment and hide all others.. you can easily achieve it by FragmentTransaction show() and hide() methods.



回答2:

Use youradapter.notifyDataSetChanged(); in onPostExecute to force a redraw of your list.