简体   繁体   中英

How to implement view pager adapter in android?

I am building an android application like TechCrunch where user can swipe the articles.

I had used view pager adapter for doing this but my application some time crash. The error I get in my logcat is :

java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 40, found: 50 Pager id: com.yslabs.yourstory:id/myviewpager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class singlearticle.SingleArticle$MyPagerAdapter at android.support.v4.view.ViewPager.populate(ViewPager.java:962) at android.support.v4.view.ViewPager.populate(ViewPager.java:914) at android.support.v4.view.ViewPager$3.run(ViewPager.java:244) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747) at android.view.Choreographer.doCallbacks(Choreographer.java:567) at android.view.Choreographer.doFrame(Choreographer.java:535) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:153) at android.app.ActivityThread.main(ActivityThread.java:5034) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Met hod.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584) at dalvik.system.NativeStart.main(Native Method)

Here is the class where I am using view page adapter

public class SingleArticleAfrica extends Activity {

ConnectionDetector checkConnection;
Boolean isInternetPresent = false;
ViewPager viewPage;
MyPagerAdapter mypageAdapter;


@SuppressWarnings("deprecation")
@SuppressLint({ "InflateParams", "SetJavaScriptEnabled", "HandlerLeak",
        "NewApi" })
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.check);
    viewPage = (ViewPager) findViewById(R.id.myviewpager);
    mypageAdapter = new MyPagerAdapter(this, ArticleDataHolder.getData());
    viewPage.setAdapter(mypageAdapter);

    viewPage.setCurrentItem(ArticleDataHolder.getPosition());

    viewPage.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // TODO Auto-generated method stub
            ArticleDataHolder.setPosition(position);
            viewPage.setCurrentItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });
     getActionBar().setBackgroundDrawable(
     new ColorDrawable(Color.parseColor("#f8f8f8")));
     ActionBar actionBar = getActionBar();
     actionBar.setDisplayHomeAsUpEnabled(true);
     ActionBar mActionBar = getActionBar();
     mActionBar.setDisplayShowHomeEnabled(true);
     mActionBar.setDisplayShowTitleEnabled(false);
     LayoutInflater mInflater = LayoutInflater.from(this);
     View mCustomView = mInflater.inflate(R.layout.customactionbar, null);
     TextView mTitleTextView = (TextView) mCustomView
     .findViewById(R.id.title_text);
     Typeface fontt = Typeface.createFromAsset(getAssets(),
     "helvetica.ttf");
     mTitleTextView.setTypeface(fontt);
     mActionBar.setCustomView(mCustomView);
     mActionBar.setDisplayShowCustomEnabled(true);
     mActionBar.setLogo(R.drawable.africaicon);

    // String htmldata =
    // "<html><style = text/css>   img{width:100%!important;height:auto!important;}iframe{max-
          width:100%;max-height:100%;}a { color:#3366CC; text-decoration: none; }</style><body   
      style = line-
  height:25px; >"

   }

  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main2, menu);
    return super.onCreateOptionsMenu(menu);
   }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.action_refresh:
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(
                Intent.EXTRA_TEXT,
                ArticleDataHolder.getData()
                        .get(ArticleDataHolder.getPosition()).getTitle()
                        + "\n"
                        + ArticleDataHolder.getData()
                                .get(ArticleDataHolder.getPosition())
                                .getPermalink());
        sendIntent.setType("text/plain");
        startActivity(sendIntent);

        return true;
    case android.R.id.home:
        onBackPressed();
        /*web1.loadUrl("");
        web1.stopLoading();*/
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
    }

  public class myWebClient extends WebViewClient

   {

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {

        // TODO Auto-generated method stub

        super.onPageStarted(view, url, favicon);

    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        // TODO Auto-generated method stub

        view.loadUrl(url);

        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {

        // TODO Auto-generated method stub

        super.onPageFinished(view, url);

        // progressBar.setVisibility(View.GONE);

    }

}

// To handle "Back" key press event for WebView to go back to previous
// screen.

@SuppressWarnings("static-access")
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)

{

    if (keyCode == event.KEYCODE_BACK) {
        /*web1.loadUrl("");
        web1.stopLoading();*/

        finish();

    }
    return super.onKeyDown(keyCode, event);

}

private class MyPagerAdapter extends PagerAdapter {

    Context context;
    List<Movie> list;

    public MyPagerAdapter(Context context, List<Movie> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    public Object instantiateItem(ViewGroup container, int position) {
        /* *Title* */

        float titleSize = 25;
        TextView titleView = new TextView(SingleArticleAfrica.this);
        Typeface fontType = Typeface.createFromAsset(getAssets(),
                "helvetica-neue-regular-1361522098.ttf");
        titleView.setTypeface(fontType);
        titleView.setTextSize(titleSize);

        titleView.setBackgroundResource(R.color.list_background);
        titleView.setTypeface(Typeface.DEFAULT_BOLD);
        titleView.setText(list.get(position).getTitle());

        /* * Date * */

        TextView dateView = new TextView(SingleArticleAfrica.this);
        dateView.setTextColor(Color.GRAY);
        dateView.setBackgroundResource(R.color.list_background);
        dateView.setTextSize(14);
        dateView.setPadding(10, 0, 0, 0);
        dateView.setTypeface(Typeface.DEFAULT_BOLD);
        dateView.setText(list.get(position).getAuthor()
                + " "
                + list.get(position)
                        .getDate()
                        .substring(0,
                                list.get(position).getDate().length() - 3));

        /* *Article Content* */

        WebView web1 = new WebView(SingleArticleAfrica.this);
        web1.setWebViewClient(new myWebClient());
        web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        web1.getSettings().setJavaScriptEnabled(true);
        web1.getSettings().setDefaultFontSize(18);
        web1.setWebChromeClient(new WebChromeClient());
        web1.getSettings().setPluginState(PluginState.ON_DEMAND);
        String c = single.content;
        c = c.replace("src=\"//", "src=\"https://");
        final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
        String htmldata = "<!DOCTYPE html><html><style = text/css> 
        img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a {     
       color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
                + list.get(position).getContent() + "</body></html>";
        web1.loadData(htmldata, "text/html; charset=utf-8", null);

        /* *Facebook Comment* */

        WebView fbCommentview = new WebView(SingleArticleAfrica.this);
        fbCommentview.setWebViewClient(new myWebClient());
        fbCommentview.getSettings()
                .setJavaScriptCanOpenWindowsAutomatically(true);
        fbCommentview.getSettings().setJavaScriptEnabled(true);
        fbCommentview.getSettings().setDefaultFontSize(18);
        fbCommentview.setWebChromeClient(new WebChromeClient());
        fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
        checkConnection = new ConnectionDetector(getApplicationContext());
        isInternetPresent = checkConnection.isConnectingToInternet();
        if (isInternetPresent) {
            // Toast.makeText(getApplicationContext(),"Internet Working",
            // Toast.LENGTH_SHORT).show();
            fbCommentview.setVisibility(View.VISIBLE);
        } else {
            // Toast.makeText(getApplicationContext(),"Internet Not Working",
            // Toast.LENGTH_SHORT).show();
            fbCommentview.setVisibility(View.GONE);
        }

        ScrollView scrollView = new ScrollView(SingleArticleAfrica.this);
        LinearLayout layout = new LinearLayout(SingleArticleAfrica.this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(titleView);
        layout.addView(dateView);
        layout.addView(web1);
        layout.addView(fbCommentview);

        scrollView.addView(layout);
        container.addView(scrollView);
        return scrollView;
    }

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

Here is getPosition class code :

  public class ArticleDataHolder {
  static List<Movie> data = new ArrayList<Movie>();

  static int position;

  public static void setData(Movie movie){
    data.add(movie);
}

public static List<Movie> getData(){
    return data;
}

public static void setPosition(int pos){
    position = pos;
}

public static int getPosition(){
    return position;
}
}

Please help me!! to make me more understanding this problem an suggested the solution.

this error say your data(list) size changed but pagerAdapter.notifyDataChanged() not called. when you setData and list changed in code you should call notifyDataChanged() after this change. where you call ArticleDataHolder.setData() ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM