RecyclerView and onclicklistner operation - java

I'm fetching RSS feed into my APP and trying to open an intent(Web browser) when a one of the news of recyclerView is clicked, but it dosn't work. and that's my code:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<FeedItem> feedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
//Call Read rss asyntask to fetch rss
ReadRss readRss = new ReadRss(this, recyclerView);
readRss.execute();
recyclerView.setOnClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
**FeedItem current=feedItems.get(position);
Uri uri = Uri.parse(current.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);**
}
});
}
}
I did even try to put the same code in my holder class but in there the startActivity() method don't work:
the above code is kinda the same but in another class:
public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> implements View.OnClickListener {
ArrayList<FeedItem> feedItems;
Context context;
public FeedsAdapter(Context context, ArrayList<FeedItem>feedItems){
this.feedItems=feedItems;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false);
view.setClickable(true);
view.setOnClickListener(this);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
YoYo.with(Techniques.FadeIn).playOn(holder.cardView);
FeedItem current=feedItems.get(position);
holder.Title.setText(current.getTitle());
holder.Description.setText(current.getDescription());
holder.Date.setText(current.getPubDate());
Picasso.get().load(current.getThumbnailUrl()).into(holder.Thumbnail);
holder.cardView.setTag(position);
Toast.makeText(context,current.getLink() ,Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return feedItems.size();
}
#Override
public void onClick(View view) {
**int position = (int) view.getTag();
FeedItem current=feedItems.get(position);
Toast.makeText(context,"The Item Clicked is: "+current.getLink() ,Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse(current.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);**
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title,Description,Date;
ImageView Thumbnail;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
Title= (TextView) itemView.findViewById(R.id.title_text);
Description= (TextView) itemView.findViewById(R.id.description_text);
Date= (TextView) itemView.findViewById(R.id.date_text);
Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
cardView= (CardView) itemView.findViewById(R.id.cardview);
}
}
}
this code:
FeedItem current=feedItems.get(position);
Uri uri = Uri.parse(current.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
is the same code that I tried in two classes in the first the error is because of RecyclerView, And in the second one it gives error because startActivity don't work in that class.
So how do I activate the clicakble news that when clicked goes to the browser?

To start activity from within the adapter class use
context.startActivity(intent);
( if thats your question.)
My suggestion
Set the click listener in onBindViewHolder(..) of your adapter on holder.itemView.setOnClick....

Related

Open 1 different activity for each cardview

I'm trying to figure how to go to another activity when I click on one item of a cardview (with recyclerview).
I searched on internet and this website and tried several options, but it isn't working (I tried only for position 0, the others will be done the same). Here, with the card 0 i try to go to "selection_niveau".
1st try : inside OnClick:
public class adapter_categorie_solo extends RecyclerView.Adapter<adapter_categorie_solo.ViewHolder> {
List<String> titles;
List<Integer> images;
LayoutInflater inflater;
public adapter_categorie_solo(Context ctx, List<String> titles, List<Integer> images){
this.titles = titles;
this.images = images;
this.inflater = LayoutInflater.from(ctx);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.cardview_solo_categorie,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.title.setText(titles.get(position));
holder.gridIcon.setImageResource(images.get(position));
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView gridIcon;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textView2);
gridIcon = itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked -> " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
if (getAdapterPosition()==0)
Intent intent = new Intent (this,selection_niveau.class);
}
});
}
}
}
I get this error :
error: variable declaration not allowed here
Intent intent = new Intent (this,selection_niveau.class);
2nd try : inside onBindViewHolder
public class adapter_categorie_solo extends RecyclerView.Adapter<adapter_categorie_solo.ViewHolder> {
List<String> titles;
List<Integer> images;
LayoutInflater inflater;
public adapter_categorie_solo(Context ctx, List<String> titles, List<Integer> images){
this.titles = titles;
this.images = images;
this.inflater = LayoutInflater.from(ctx);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.cardview_solo_categorie,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.title.setText(titles.get(position));
holder.gridIcon.setImageResource(images.get(position));
Intent intent;
if(position == 0)
intent = new Intent(this, selection_niveau.class);
holder.itemView.setOnClickListener(new View.OnClickListener(){
#Override public void onClick(View v){
Context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView gridIcon;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textView2);
gridIcon = itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked -> " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
And I get this error :
error: no suitable constructor found for Intent(adapter_categorie_solo,Class<selection_niveau>)
intent = new Intent(this, selection_niveau.class);
^
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; adapter_categorie_solo cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; adapter_categorie_solo cannot be converted to Context)
I tried to change "this" to only "context", but it doesn't work either.
These are some of the solutions I found on internet and here, but none is working and I can't really understand why as being a beginner.
Inside the onClick() callback this keyword will points to the anonymous inner class of the View.OnClickListener; so you need to change to a context by using v.getContext() instead.
Apply this by replacing itemView.setOnClickListener with:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked -> " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
if (getAdapterPosition()==0) {
Intent intent = new Intent (v.getContext(), selection_niveau.class);
}
}
});
Intent constructor requires a context as the first argument, but this in the ViewHolder refers to the instance of ViewHolder, So you need to get context from the view or use the context reference you got in the constructor of the adapter_categorie_solo.
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView gridIcon;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textView2);
gridIcon = itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked -> " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
if (getAdapterPosition()==0)
{
Intent intent = new Intent (ctx,selection_niveau.class);
ctx.startActivity(intent);
}
}
});
}
}
Using switch instead of if will be an optimal approach if you want to start different activity based on click position.
use context in Intent instead of this
if(position == 0)
intent = new Intent(context, selection_niveau.class);

Convert ListView to RecyclerView

i have a list view in my app.
I want to change it to an recycler view, but even with different tutorials i dont get it.
I was using this: https://www.spreys.com/listview-to-recyclerview/
I failed with the "getView" part here.
Here is my code of the ListActivity and LeagueArrayAdapter.
Thanks for your help.
ListActivity:
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayAdapter adapter;
private final int REQUEST_CODE_EDIT = 1;
private static LeagueDAO leagueDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
if (allLeagues1.size() == 0) {
leagueDAO.insert(new League("HVM Landesliga 19/20","https://hvmittelrhein-handball.liga.nu/cgi-bin/WebObjects/nuLigaHBDE.woa/wa/groupPage?championship=MR+19%2F20&group=247189"));
allLeagues1 = leagueDAO.getLeagues();
}
adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
ListView lv = findViewById(R.id.league_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
registerForContextMenu(lv);
Button btn_league_add = findViewById(R.id.btn_league_add);
btn_league_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this, EditActivity.class);
startActivity(intent);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu contMenu, View v,
ContextMenu.ContextMenuInfo contextmenuInfo) {
super.onCreateContextMenu(contMenu, v, contextmenuInfo);
getMenuInflater().inflate(R.menu.team_list_context_menu, contMenu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo acmi=
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
League league = (League)adapter.getItem(acmi.position);
switch (item.getItemId()) {
case R.id.evliconit_edit:
editEntry(league, acmi.position);
return true;
case R.id.evliconit_del:
leagueDAO.delete(league);
adapter.remove(league);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
League team = (League)adapter.getItem(position);
editEntry(team, position);
}
private void editEntry(League league, int position) {
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("team", league);
intent.putExtra("position", position);
startActivityForResult(intent, REQUEST_CODE_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE_EDIT && resultCode == RESULT_OK && intent != null) {
Bundle extras = intent.getExtras();
int position = extras.getInt("position");
League league = (League) adapter.getItem(position);
league.setLeague_name(extras.getString("league_name"));
league.setLeague_url(extras.getString("league_url"));
adapter.notifyDataSetChanged();
}
}
#Override
protected void onRestart() {
super.onRestart();
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
ListView lv = findViewById(R.id.league_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
registerForContextMenu(lv);
}
LeagueArrayAdapter:
public class LeagueArrayAdapter extends ArrayAdapter<League> {
private List<League> leagues;
private Context context;
private int layout;
public LeagueArrayAdapter(Context context, int layout, List<League> leagues) {
super(context, layout, leagues);
this.context = context;
this.layout = layout;
this.leagues = leagues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
League league = leagues.get(position);
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(layout, null);
TextView tv_name = convertView.findViewById(R.id.tv_name);
TextView tv_url = convertView.findViewById(R.id.tv_url);
tv_name.setText(league.getLeague_name());
tv_url.setText(league.getLeague_url());
return convertView;
}
}
Update: app crashed when opened the activity
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayAdapter adapter;
private final int REQUEST_CODE_EDIT = 1;
private static LeagueDAO leagueDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
if (allLeagues1.size() == 0) {
leagueDAO.insert(new League("HVM Landesliga 19/20","https://hvmittelrhein-handball.liga.nu/cgi-bin/WebObjects/nuLigaHBDE.woa/wa/groupPage?championship=MR+19%2F20&group=247189"));
allLeagues1 = leagueDAO.getLeagues();
}
// adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
RecyclerView lv = findViewById(R.id.league_list);
lv.setHasFixedSize(true);
lv.setLayoutManager(new LinearLayoutManager(this));
lv.setAdapter(new LeagueArrayAdapter(allLeagues1));
// lv.setOnItemClickListener(this);
registerForContextMenu(lv);
Button btn_league_add = findViewById(R.id.btn_league_add);
btn_league_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this, EditActivity.class);
startActivity(intent);
}
});
}
I reconstructed your ListView Adapter using RecyclerView.Adapter.
onCreateView is called for every visible container on your screen. If your screen can show 10 rows of data RecyclerView makes 11 - 12 containers (ViewHolder)
onBindView updates those containers with new data when you scroll.
MyViewHolder is the object that holds data about every row of data (container)
static class and bind() function inside to avoid any memory leak in your adapter.
We have access to Context in RecyclerView.Adapter using itemView and parent
itemView is the inflated View for each container (ViewHolder).
Initialize your Views inside ViewHolder's constructor so they get assigned once.
public class LeagueArrayAdapter extends RecyclerView.Adapter<LeagueArrayAdapter.MyViewHolder> {
private ArrayList<League> leagues;
public LeagueArrayAdapter(ArrayList<League> leagues) {
this.leagues = leagues;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.row_league, parent, false);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.bind(leagues.get(position));
}
#Override
public int getItemCount() {
return 0;
}
static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_name;
TextView tv_url;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tv_name);
tv_url = itemView.findViewById(R.id.tv_url);
}
void bind(League league) {
tv_name.setText(league.getLeague_name());
tv_url.setText(league.getLeague_url());
}
}
}
Your Activity:
LinearLayoutManager for a linear layout
GridLayoutManager for a grid layout
setHasFixedSize() enhances your RecyclerView's speed if you are sure the RecyclerView itself won't change width or height.
public class LeagueActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_ACTIVITY_LAYOUT_ID);
...
RecyclerView recyclerView = findViewById(R.id.YOUR_RECYCLER_VIEW_ID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new LeagueArrayAdapter(SEND_YOUR_ARRAY_OF_LEAGUE));
}
}
I suggest checking the Groupie Lbrary, it works with recyclerView and it makes life much easier for you, here is an example of how you can use it (I'm writing the code in kotlin but it shouldn't be that different from java)
first, add those lines to your Build.gradle (app) file
implementation 'com.xwray:groupie:2.3.0'
implementation 'com.xwray:groupie-kotlin-android-extensions:2.3.0'
then inside your activity create an adapter then set the adapter to your recyclerView
val myAdapter = GroupAdapter<ViewHolder>()
recyclerView.adapter = myAdapter
and just like this you set the adapter to your recyclerView, but you have to create "Items" to put inside the recyclerView. you can create an Item like so
class MyItem: Item() {
override fun getLayout() = R.layout.layout_seen
override fun bind(viewHolder: ViewHolder, position: Int){
}
}
in the getLayout method, you return the layout that you to display inside the recyclerView,
you can use the bind method to do any kind of modifications we want to apply to our layout that we are displaying.
lastly, we can add our items to the adapter this way
myAdapter.add(MyItem())
myAdapter.notifyDataSetChanged()
for more details check the library, in here I just explained how you can simply add an item to your RecyclerView

How to fix code to display data from Firebase?

I already ask similar question, When i click on textview(header_news from firebase), i switch to another activity and load data from Firebase. In another activity i get the same data(1 news by id). But i want to be displayed main_news. I know where problem, but i dont know how to fix it. I think problem in bindviewholder becouse i dont add myViewHolder.main_news.setText(Mnews.get(i).getMain_news()); But i cant to add, becouse its be displayed on header news.... P.S Sorry for my english i hope you understand me.
Adapter Code:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
Context Mcontext;
ArrayList<News> Mnews;
public NewsAdapter(Context Mcontext, ArrayList<News> Mnews)
{
this.Mnews = Mnews;
this.Mcontext = Mcontext;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(Mcontext).inflate(R.layout.news_view, viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
final News news = Mnews.get(i);
myViewHolder.news_date.setText(Mnews.get(i).getDatenews());
myViewHolder.news_header.setText(Mnews.get(i).getHeader_news());
Picasso.get().load(Mnews.get(i).getImageURL()).into(myViewHolder.news_picture);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Mcontext, NewsActivity.class);
intent.putExtra("idnews", news.getIdnews());
Mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return Mnews.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView news_date, news_header, main_news;
ImageView news_picture;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_header = (TextView) itemView.findViewById(R.id.news_header);
news_picture = (ImageView) itemView.findViewById(R.id.news_picture);
}
}
}
And Activity code:
public class NewsActivity extends AppCompatActivity {
String idnews;
TextView main_news;
DatabaseReference reference;
TextView news_date;
RecyclerView recyclerView;
Intent intent;
ArrayList<News> Nlist;
NewsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
main_news = findViewById(R.id.main_news);
intent = getIntent();
idnews = intent.getStringExtra("idnews");
Nlist = new ArrayList<News>();
reference = FirebaseDatabase.getInstance().getReference("News").child(idnews);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Nlist.clear();
News news = dataSnapshot.getValue(News.class);
main_news.setText(news.getNews_main());
Nlist.add(news);
adapter = new NewsAdapter(getApplicationContext(), Nlist);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(NewsActivity.this, "Что то не так", Toast.LENGTH_SHORT).show();
}
});
}
}
My database struct
I hope you can help me.

How to create an Intent within a fragment class

I have managed to create a tabbed activity using recycle view and have made a list-view in each fragment, now I have the lists I need to make the cards in the fragment clickable and create an intent to start a new activity. I have tried on-click method and onListItemClick even though I knew that would not work.
Basically I need to create one more layer of lists for each fragment which will lead to a list of actions (webviews, Maps, and information).
Example Code is below
ublic class LOneFragment extends Fragment {
public LOneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"League One News", "AFC Wimbledon", "Blackburn Rovers", "Blackpool", "Bradford City", "Bristol Rovers", "Bury", "Charlton Athletic", "Doncaster Rovers", "Fleetwood Town",
"Gillingham", "Milton Keynes Dons", "Northampton Town", "Oldham Athletic", "Oxford United", "Peterborough United", "Plymouth Argyle", "Portsmouth", "Rochdale", "Rotherham United",
"Scunthorpe United", "Shrewsbury Town", "Southend United", "Walsall", "Wigan Athletic"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
public void onListItemClick(ListView l, View v, int position, long id) {
if (position == 3) {
Intent intent = new Intent(getContext(), Bradford.class);
startActivity(intent);
}
My adaptor class
public class MyAdapter extends RecyclerView.Adapter {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MyAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
}
This works perfect for me.
1) Create method in viewholder class which will take position, get array item from position and use the way you like.
2) Access it in onBindViewHolder method with itemView instance which is the full row at given position,
public class MyAdapter extends RecyclerView.Adapter {
private String[] mDataset;
public MyAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.bindCliks(groupItem);
}
});
#Override
public int getItemCount() { return mDataset.length; }
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
public void bindCliks(int position) {
Intent intent = new Intent(context,
OtherActivity.class);
//use number here to get your string item and use it to other activity.
context.startActivity(intent);
}
}

How to pass data from Recyclerview onClickLister to other Activity

I want to pass data from onclick recycler view main activity to other activity(exoplayer).
I created onimageclicklistener class and then I declared my onimageclicklistener in the adapter class. Then I implement that listener in main activity and implemented on image click method, now I am blank and do not know what do.
I will appreciate if someone helps.
interface class:
public interface OnImageClickListener
{
void onImageClick(String imageData);
}
adapter:
public class SongAdapter extends RecyclerView.Adapter {
private Context context;
private List<Datum> datums;
//imagelistener define
private OnImageClickListener onImageClickListener;
//3rd argument is listener
public SongAdapter(Context context, List<Datum> datums, OnImageClickListener onImageClickListener) {
this.context = context;
this.datums = datums;
this.onImageClickListener = onImageClickListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Datum datum = datums.get(position);
Glide.with(context).load(datums.get(position).getThumbnail()).into(holder.thumbnail);
holder.title.setText(datum.getTitle());
holder.artist.setText(datum.getArtist());
// holder.duration.setText(datum.getDuration());
holder.duration.setText(Integer.toString(datum.getDuration()));
//imageview interface pass
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onImageClickListener.onImageClick(datum.getUrl());
}
});
}
#Override
public int getItemCount() {
return datums.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView thumbnail;
TextView title;
TextView artist;
TextView duration;
public ViewHolder(#NonNull View itemView) {
super(itemView);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
title = (TextView) itemView.findViewById(R.id.title);
artist = (TextView) itemView.findViewById(R.id.artist);
duration = (TextView) itemView.findViewById(R.id.duration);
}
}
}
Mainactivity:
//imageclick listener
#Override
public void onImageClick(String imageData) {
Intent i = new Intent(MainActivity.this,exoplayer.class);
startActivity(i);
}
I want to send data to exoplayer class.
Using Intent Extras
#Override
public void onImageClick(String imageData) {
Intent i = new Intent(MainActivity.this,exoplayer.class);
intent.putExtra("YOUR_KEY_STRING", imageDate);
startActivity(i);
}
And then from exoplayer Activity, you retrieve it in the onCreate() method as follows :
String imageData = getIntent().getStringExtra("YOUR_KEY_STRING");
Using bundle
#Override
public void onImageClick(String imageData) {
Intent i = new Intent(MainActivity.this,exoplayer.class);
Bundle bundle = new Bundle();
bundle.putString("imageDataKey", imageData);
intent.putExtra("YOUR_BUNDLE_KEY", bundle);
startActivity(i);
}
And then from your exoactivity you retrieve it as follows :
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getStringExtra("YOUR_BUNDLE_KEY");
String imageData = bundle.getString("imageDataKey");
}
Using intent we can send data
//imageclick listener
#Override
public void onImageClick(String imageData) {
Intent i = new Intent(MainActivity.this,exoplayer.class);
i.putExtra("data",imageData);
startActivity(i);
}

Categories

Resources