Raul Figueira Raul Figueira - 22 days ago 5
Android Question

Using startActivity outside an Activity

I am inside a class that doesn't extends an Activity and I am trying to access the method startActivity and also MainActivity to make an intent, like this:

Intent intent = new Intent(MainActivity, MusicasPlaylistActivity.class);
PlayList item = (PlayList) adapter.getItem(position);
intent.putExtra("id", item.getId());
startActivity(intent);


But inside my class I cannot see the method "startActivity" and I cannot see "MainActivity" neither because my class doesn't extends an Activity because it already extends another class (called RecyclerView.ViewHolder).

How can I access the startActivity method and the MainActivity to make the intent?

Answer

How can I access the startActivity method and the MainActivity to make the intent?

you need a Context object for that. You can either pass it to the constructor or, in your case, use RecyclerView.ViewHolder itemView to retrieve it. E.g.

Intent intent = new Intent(itemView.getContext(), MusicasPlaylistActivity.class);
PlayList item = (PlayList) adapter.getItem(position);
intent.putExtra("id", item.getId());
itemView.getContext().startActivity(intent);

itemView is the public final View hold by RecyclerView.ViewHolder

Comments