PagerAdapter 问题

Issue with PagerAdapter

我尝试从 firebase 数据库加载数据库并得到这个异常。这是关于notifyDataSetChanged。我试图在 getCount() 中输入 SlideShowAapter,但没有成功。

例外情况:

java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! 
Expected adapter item count: 0, found: 1 Pager id: com.example.dave.lomoapp:id/slideShow Pager class: class android.support.v4.view.ViewPager 
Problematic adapter: class com.example.davenguyen.lomoapp.SlideShowAdapter
      at android.support.v4.view.ViewPager.populate(ViewPager.java:1135)
      at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
      at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
      at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:616)
      at com.example.davenguyen.lomoapp.HomeFragment.run(HomeFragment.java:71)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:148)
      at android.app.ActivityThread.main(ActivityThread.java:7331)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

这是我的 SlideShowAdapter

public class SlideShowAdapter extends PagerAdapter {

private boolean doNotifyDataSetChangedOnce = false;
private ArrayList<Genre> genresList;
private LayoutInflater inflater;
private Context context;

public SlideShowAdapter(Context context, ArrayList<Genre> images) {
    this.context = context;
    this.genresList =images;
    inflater = LayoutInflater.from(context);
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
}

@Override
public int getCount()
{
    if (doNotifyDataSetChangedOnce) {
        doNotifyDataSetChangedOnce = false;
        notifyDataSetChanged();
    }
    return genresList.size();
}

@Override
public Object instantiateItem(ViewGroup view, int position) {
    View myImageLayout = inflater.inflate(R.layout.slide, view, false);
    ImageView myImage = (ImageView) myImageLayout
            .findViewById(R.id.slideShowImg);
    Picasso.with(context).load(genresList.get(position).getImage()).into(myImage);
    view.addView(myImageLayout, 0);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    return myImageLayout;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view.equals(object);
}

}

这是一个包含我的自定义适配器的片段

public class HomeFragment extends Fragment {

private static ViewPager mPager;
private static int currentPage = 0;

private ArrayList<Genre> genreList = new ArrayList<Genre>();

DatabaseReference mref;

public HomeFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v =inflater.inflate(R.layout.fragment_home, container, false);
    return v;
}

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


    loadImage();

    mPager = (ViewPager) view.findViewById(R.id.slideShow);
    mPager.setAdapter(new SlideShowAdapter(getActivity(), genreList));
    CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
    indicator.setViewPager(mPager);

    // Auto start of viewpager
    final Handler handler = new Handler();
    final Runnable Update = new Runnable() {
        public void run() {
            if (currentPage == genreList.size()) {
                currentPage = 0;
            }
            mPager.setCurrentItem(currentPage++, true);
        }
    };
    Timer swipeTimer = new Timer();
    swipeTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(Update);
        }
    }, 2500, 2500);
}

private void loadImage() {
    // Get a reference to our genres
    mref = FirebaseDatabase.getInstance().getReference().child("genres");
    // Attach a listener to read the data at our genres reference
    mref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            genreList.add (dataSnapshot.getValue(Genre.class));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i("READ_FAIELD","The read failed: " + databaseError.getCode());
        }
    });
}

}

提前致谢

这样写:

SlideShowAdapter adapter=new SlideShowAdapter(getActivity(), genreList);
mPager.setAdapter(adapter);
adapter.notifyDataSetChanged();

而不是

mPager.setAdapter(new SlideShowAdapter(getActivity(), genreList));

尝试使用以下方法更改 instantiateItem:

View myImageLayout = inflater.inflate(R.layout.slide, view, false);
    ImageView myImage = (ImageView) myImageLayout
            .findViewById(R.id.slideShowImg);
    Picasso.with(context).load(genresList.get(position).getImage()).into(myImage);

    .
myImageLayout.addView(myImage, 0);
    myImageLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    return myImageLayout;

并删除:

if (doNotifyDataSetChangedOnce) {
        doNotifyDataSetChangedOnce = false;
        notifyDataSetChanged();
    }

我的猜测是问题出在您的适配器中的标志 doNotifyDataSetChangedOnce。尝试删除 if 并在加载图片后调用 adapter.notifyDataSetChanged()(在 onDataChange 中)。

如果这解决了崩溃问题但 viewPager 未更新,您可能需要在适配器中添加此代码:

    public int getItemPosition(Object object) { 
        return POSITION_NONE;
    }