Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

android - How to update fragment's data used in ViewPager? View is not showing the updated data

I know the same question has been asked so many times but I am not able to solve my issue.

I have created an Activity which has a ViewPager which should have 4 Pages.

I am using the same Fragment for all pages. The Fragment has a GridView which should be updated whenever I swipe to the other page.

Following are the classes & XML layouts I have used to create it.

Activity layout activity_discover.xml

 <android.support.v4.view.ViewPager
            android:id="@+id/activity_discover_view_pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <android.support.v4.view.PagerTabStrip
                android:id="@+id/activity_discover_pager_tab_strip"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:textColor="@color/black"
                android:textSize="@dimen/header_text" />
        </android.support.v4.view.ViewPager>
</RelativeLayout>

Activity DiscoverActivity.java

public class DiscoverActivity extends FragmentActivity implements OnClickListener, OnPageChangeListener
{
    private final static String TAG = "DiscoverActivity";
    private UtilDialog utilDialog;

    MPagerAdapter adapterViewPager;
    PagerTabStrip pagerTabStrip;
    ViewPager viewPager;

    public ArrayList<String> listCategory;


    LMProgressDialog progressDialog;
    private RelativeLayout relativeCountry;
    private RelativeLayout relativeCity;
    private TextView tvCountry;
    private TextView tvCity;

    private String selectedCategory;
    private int selectedCityID = 0;
    private int selectedCategoryID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discover);
        initParameters();
        initView();
    }

    void initParameters()
    {
        progressDialog = new LMProgressDialog(this);

        utilDialog = new UtilDialog(this);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
        editor.commit();
        selectedCategory = getResources().getString(R.string.adventure);

        listCategory = new ArrayList<String>();
        listCategory.add(getResources().getString(R.string.adventure));
        listCategory.add(getResources().getString(R.string.night_life));
        listCategory.add(getResources().getString(R.string.life_styles));
        listCategory.add(getResources().getString(R.string.events));
    }

    void initView()
    {

        viewPager = (ViewPager) findViewById(R.id.activity_discover_view_pager);
        viewPager.setOnPageChangeListener(this);
        adapterViewPager = new MPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapterViewPager);

        pagerTabStrip = (PagerTabStrip) findViewById(R.id.activity_discover_pager_tab_strip);
        pagerTabStrip.setTabIndicatorColor(getResources().getColor(R.color.white));

                }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    public class MPagerAdapter extends FragmentPagerAdapter
    {
        private Map<Integer, String> mFragmentTags;
        private FragmentManager mFragmentManager;

        public MPagerAdapter(FragmentManager fm)
        {
            super(fm);
            mFragmentManager = fm;
            mFragmentTags = new HashMap<Integer, String>();
        }

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

        @Override
        public Fragment getItem(int position)
        {
             Fragment fragment = Fragment.instantiate(DiscoverActivity.this,
             FragmentMediaContent.class.getName(), null);

            return fragment;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            Object obj = super.instantiateItem(container, position);
            if (obj instanceof Fragment)
            {
                // record the fragment tag here.
                Fragment f = (Fragment) obj;
                String tag = f.getTag();
                mFragmentTags.put(position, tag);
            }
            return obj;
        }

        public Fragment getFragment(int position)
        {
            String tag = mFragmentTags.get(position);
            if (tag == null)
                return null;
            return mFragmentManager.findFragmentByTag(tag);
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return listCategory.get(position).toString().toUpperCase();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0)
    {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2)
    {

    }

    @Override
    public void onPageSelected(int position)
    {
        selectedCategoryID = position;
        selectedCategory = listCategory.get(position);
        try
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Constants.CITY_ID, selectedCityID);
            jsonObject.put(Constants.CATEGORY, selectedCategory);
            makeJsonObjectRequest(Request.Method.POST, jsonObject, API.URL_LOAD_MEDIA);
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    void prepareMediaList(JSONArray arrayMedia)
    {
        int noOfMedia = arrayMedia.length();

        ArrayList<MediaType> listMedia = new ArrayList<MediaType>();
        for (int i = 0; i < noOfMedia; i++)
        {
            try
            {
                JSONObject objectMedia = arrayMedia.getJSONObject(i);
                int id = objectMedia.getInt(Constants.ID);
                String category = objectMedia.getString(Constants.CATEGORY);
                String mediaType = objectMedia.getString(Constants.MEDIA_TYPE);
                int cityID = objectMedia.getInt(Constants.CITIES_ID);
                String path = objectMedia.getString(Constants.PATH);
                String thumbnailPath = objectMedia.getString(Constants.THUMBNAIL_PATH);
                String description = objectMedia.getString(Constants.DESCRIPTION);
                int userID = objectMedia.getInt(Constants.USERS_ID);

                listMedia.add(new MediaType(id, mediaType, path, category, userID, cityID, 0, description, thumbnailPath));
            } catch (JSONException e)
            {
                e.printStackTrace();
            }
        }

        FragmentMediaContent fragment = (FragmentMediaContent) adapterViewPager.getFragment(selectedCategoryID);
        Log.i(TAG, "fragment: " + fragment);
        fragment.updateData(listMedia, selectedCategory);
    }
}

Fragment class FragmentMediaContent.java:

public class FragmentMediaContent extends Fragment
{
    private final static String TAG = "FragmentMediaContent";
    public static final String FRAGMENT_POSITION = null;

    private GridView gridView;
    private UtilDialog utilDialog;
    private SharedPreferences preferences;
    private Editor editor;

    private ArrayList<MediaType> listMedia;
    MediaAdapter mediaAdapter;

    private int cityID;
    private String category;

    LMProgressDialog progressDialog;
    TextView tvTest;

     public static FragmentMediaContent newInstance(int num)
     {
         FragmentMediaContent f = new FragmentMediaContent();
         return f;
     }

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

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        initParameters();
        initViews();
    }

    void initParameters()
    {
        getSize();
        listMedia = new ArrayList<MediaType>();
        utilDialog = new UtilDialog(getActivity());
        progressDialog = new LMProgressDialog(getActivity());
        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        editor = preferences.edit();
        mediaAdapter = new MediaAdapter(getActivity(), listMedia);
    }

    void initViews()
    {
        tvTest = (TextView) getActivity().findViewById(R.id.fragment_media_content_tv_test);
        tvTest.setText(category+" no of media");
        tvTest.setVisibility(View.GONE);
        gridView = (GridView) getActivity().findViewById(R.id.fragment_media_content_grid_view);
        gridView.setAdapter(mediaAdapter);

    }


    /**
     * MediaAdapter : ArrayAdapter class which prepares view for list of
     * MediaType.
     * 
     */
    class MediaAdapter extends ArrayAdapter<MediaType>
    {
        MediaAdapter(Context context, ArrayList<MediaType> list)
        {
            super(context, R.layout.cell_media_view, R.id.cell_media_view_tv_test, list);
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            View row = super.getView(position, convertView, parent);
            MediaViewHolder holder = (MediaViewHolder) row.getTag();
            if (holder == null)
            {
                holder = new MediaViewHolder(row);
                row.setTag(holder);
            }

            final MediaType mediaType = getMedia(position, this);
            String thumbnailPath = mediaType.getThumbnailPath();
            String path = mediaType.getPath();
            String type = mediaType.getMediaType();

            // imageLoader.get(type.equals(Constants.TYPE_IMAGE) ? path :
            // thumbnailPath, ImageLoader.getImageListener(holder.ivMedia,
            // R.drawable.logo, R.drawable.ic_launcher));

            holder.ivType.setVisibility(type.equals(Constants.TYPE_IMAGE) ? View.GONE : View.VISIBLE);

            holder.ivMedia.setLayoutParams(new FrameLayout.LayoutParams(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
            Picasso.with(getActivity()).load(type.equals(Constants.TYPE_IMAGE) ? path : thumbnailPath).noFade().centerCrop().resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE).placeholder(R.drawable.loading)
                    .error(R.drawable.no_image).into(holder.ivMedia);

            return row;
        }
    }

    public void updateData(ArrayList<MediaType> listMedia, String category)
    {
        Log.i(TAG, "Updating data for: " + category);
        Log.i(TAG, "No of media items: " + listMedia.size());
        // this.listMedia.clear();
        // this.listMedia.addAll(listMedia);
        // mediaAdapter.notifyDataSetChanged();

        mediaAdapter = new MediaAdapter(getActivity(), listMedia);
        gridView.setAdapter(mediaAdapter);
        tvTest.setText(category + ", No of Media : " + listMedia.size());
    }

    int THUMBNAIL_SIZE = 200;

    /**
     * @param position
     * @return MediaType object from specified position
     */
    private MediaType getMedia(int position, MediaAdapter mediaAdapter)
    {
        return (MediaType) mediaAdapter.getItem(position);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After checking your code more in details i see you do not require to re-initliaze your MediaAdapter inside updateData method.

You simply require to update your updateData as

listMedia.clear();
this.listMedia.addAll(listMedia);
mediaAdapter.notifyDatasetChanged();

This will reload your data in gridview. Change i suggested will refresh the data in your arraylist which is being used for rendering gridview and then you notify your mediaAdapter to reload the list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...