3

How do I start a new Activity using Intent from PagerAdapter class? This is how my ViewPagerAdapter class looks like.

public class ViewPagerAdapter extends PagerAdapter

This is how I am trying to start new activity in the OnClickListner method of the ViewPagerAdapter

@Override
        public void onClick(View v) {
           // Page is clicked
           NewsItem item = ViewPagerAdapter.this.newsItems.get(position);
           Log.w("TAP ON NEWS ITEM ", item.getTitle());

           // start ImageViewer Activity
            Intent readMore = new Intent(getActivity(), ReadMoreActivity.class);

            startActivity(readMore);

        }
    }); 
CuriousSuperhero
  • 6,531
  • 4
  • 27
  • 50
smartsanja
  • 4,413
  • 9
  • 58
  • 106
  • is your ViewPagerAdapter is out of some activity or inside activity – Pankaj Nimgade Mar 30 '15 at 04:57
  • if you're getting a crash while firing the intent; read the log. It maybe telling you to set a new task flag, which will look like `readMore.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)` – Rakeeb Rajbhandari Mar 30 '15 at 05:02
  • @PankajNimgade Its a separate class. I am passing the array adapter from couple of activities to populate this ViewPagerAdapter – smartsanja Mar 30 '15 at 05:06
  • @RakeebRajbhandari It's a compilation error. I cannot implement the Intent readMore = new Intent(getActivity(), ReadMoreActivity.class); method – smartsanja Mar 30 '15 at 05:07
  • @sajaz, as you know to move to another activity you would need context, what you can do is supply Context object to constructor of your ViewPagerAdapter, that way you will have the context to use and you can write your code as in your question and it will work :) – Pankaj Nimgade Mar 30 '15 at 05:08

2 Answers2

3

getActivity() and startActivity method's not available in PagerAdapter. so use v.getContext() for preparing Intent and calling startActivity method :

Intent readMore = new Intent(v.getContext(), ReadMoreActivity.class);
v.getContext().startActivity(readMore);
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • 1
    Thanks a lot for the guidance. I am moving from iOS development to Android. These are the beginner days of mine. I am still struggling on those sdk and syntax differences – smartsanja Mar 30 '15 at 05:12
0
public class ViewPagerAdapter extends PagerAdapter{
Context _context;
public ViewPagerAdapter (Context context){
_context = context;
}
}

and rest of your code is in your question, and even the other answer would work :),

Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30