RecyclerVIew onItemClickListener Not working - java

I am working on RecyclerView and try to using on click listener for each item of recyclcerview using Interface
Here is my Activity class:
public class LegacyHomeActivity extends ActivityBaseDrawer {
private List<LegacyVideo> legacyVideoList = null;
private List<Video> videoList = new ArrayList<>();
private RecyclerView mRecyclerView;
private LegacyModeHomeAdapter adapter;
#Override
public void onNetworkStateChanged(boolean connected) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
isLegacyMode = true;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_legacy_home);
if (getSupportActionBar() != null) {
setTitle(getString(R.string.footy_legacy_home));
}
ImageView legacy_live_score_imageView = (ImageView) findViewById(R.id.legacy_live_score_imageView);
legacy_live_score_imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LegacyHomeActivity.this, LegacyLiveScoreActivity.class));
}
});
ImageView legacy_highlight_imageView = (ImageView) findViewById(R.id.legacy_highlight_imageView);
legacy_highlight_imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LegacyHomeActivity.this, LegacyHighlightsActivity.class));
}
});
ImageView legacy_news_imageView = (ImageView) findViewById(R.id.legacy_news_imageView);
legacy_news_imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LegacyHomeActivity.this, LegacyNewsActivity.class));
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.legacy_mood_recyclerview);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
adapter = new LegacyModeHomeAdapter(getApplicationContext(), itemClickListener);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setHasFixedSize(true);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.ThemeColor,
R.color.ThemeColor, R.color.ThemeColor);
swipeRefreshLayout
.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getLegacyVideoList();
}
});
circularProgressView = (CircularProgressView) findViewById(R.id.circularProgressView);
showLoadingProgress();
getLegacyVideoList();
}
LegacyVideoClickListener itemClickListener = new LegacyVideoClickListener() {
#Override
public void onItemClickListener(int position) {
Video video = videoList.get(position);
VideoPlayerUtil.initVideoPLayer(video, LegacyHomeActivity.this);
}
};
private void getLegacyVideoList() {
FootyLightAPI api = new FootyLightAPI(getApplicationContext(), mResponseListener);
api.getLegacyHomeVideoList();
}
private final FootyLightAPI.ResponseListener mResponseListener = new FootyLightAPI.ResponseListener() {
#Override
public void getResponse(int apiId, final String response) {
switch (apiId) {
case R.integer.ApiLegacyVideoList:
Log.e("Legacy ............", "Response:................" + response);
try {
final ObjectMapper mapper = new ObjectMapper();
legacyVideoList = mapper.readValue(response, new TypeReference<List<LegacyVideo>>() {
});
if (legacyVideoList != null && legacyVideoList.size() > 0) {
videoList.clear();
for (LegacyVideo video : legacyVideoList) {
Log.e("Legacy video", "" + video.getTitle());
Video videoItem = new Video();
if (video.getItemType().equalsIgnoreCase("video")) {
videoItem.setTitle(video.getTitle());
videoItem.setLink(video.getLink());
videoItem.setThumb(video.getThumb());
videoItem.setContentType(video.getContentType());
videoItem.setContentUrl(video.getContentUrl());
videoItem.setDmcaLabel(video.getDmcaLabel());
videoItem.setDmcaContent(video.getDmcaContent());
videoItem.setDmcaDisclaimer(video.getDmcaDisclaimer());
videoItem.setDisplayType(video.getDisplayType());
videoList.add(videoItem);
}
}
}
Log.e("VideoList", "........." + videoList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
showVideoAdapter();
hideLoadingProgress();
}
});
} catch (Exception e) {
}
break;
default:
break;
}
}
#Override
public void getError(int apiId, int errorCode) {
}
#Override
public void getResponse(String trackingStr, int apiId, String response) {
}
#Override
public void getError(String trackingStr, int apiId, int errorCode) {
}
};
public void showVideoAdapter() {
if (adapter != null) {
adapter.setVideos(videoList);
}
}
}
And here is my Adapter Class
public class LegacyModeHomeAdapter extends RecyclerView.Adapter<LegacyModeHomeAdapter.ItemViewHolder> {
private List<Video> videoList;
private Context mContext;
private LegacyVideoClickListener onVideosRVItemClickListener;
private LayoutInflater getLayoutInflater() {
return LayoutInflater.from(mContext);
}
public LegacyModeHomeAdapter(Context mContext, LegacyVideoClickListener onVideosRVItemClickListener) {
this.mContext = mContext;
this.onVideosRVItemClickListener = onVideosRVItemClickListener;
}
public void setVideos(List<Video> videosList) {
this.videoList = videosList;
notifyDataSetChanged();
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.layout_legacy_mode_home_video_item, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
Video video = videoList.get(position);
Picasso.with(mContext).load(video.getThumb()).into(holder.categoryImage);
holder.categoryName.setText(video.getTitle());
holder.title_image_btn.setText(video.getDisplayType());
holder.VideosItemClickListener(position, onVideosRVItemClickListener);
}
#Override
public int getItemCount() {
if (videoList != null) {
return videoList.size();
}
return 0;
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView categoryName;
private ImageView categoryImage;
private Button title_image_btn;
public ItemViewHolder(View itemView) {
super(itemView);
categoryName = (TextView) itemView.findViewById(R.id.categoryName);
categoryImage = (ImageView) itemView.findViewById(R.id.categoryImage);
title_image_btn = (Button) itemView.findViewById(R.id.title_image_btn);
}
public void VideosItemClickListener(final int position, final LegacyVideoClickListener videosRVItemClickListener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videosRVItemClickListener.onItemClickListener(position);
}
});
}
}
}
And finally i am using this interface for listener :
public interface LegacyVideoClickListener {
public void onItemClickListener(int position);
}
This procedure working fine all of my other portion of app but not working this case. I don't know where is the problem . Please help me .

You this approach:
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final String element = mDataset[position];
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your code
}
});
}

Pass onVideosRVItemClickListener in your ItemViewHolder constructor.
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.layout_legacy_mode_home_video_item, parent, false);
return new ItemViewHolder(view, onVideosRVItemClickListener);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
Video video = videoList.get(position);
Picasso.with(mContext).load(video.getThumb()).into(holder.categoryImage);
holder.categoryName.setText(video.getTitle());
holder.title_image_btn.setText(video.getDisplayType());
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView categoryName;
private ImageView categoryImage;
private Button title_image_btn;
public ItemViewHolder(View itemView, final LegacyVideoClickListener videosRVItemClickListener) {
super(itemView);
categoryName = (TextView) itemView.findViewById(R.id.categoryName);
categoryImage = (ImageView) itemView.findViewById(R.id.categoryImage);
title_image_btn = (Button) itemView.findViewById(R.id.title_image_btn);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videosRVItemClickListener.onItemClickListener(getAdapterPosition());
}
});
}
}

Check this sample
OnCLick can be achived using Custom Interface
interface Listener {
void performOperation(int Position);
}
in Your Adapter
private Listener mListener;
In your Adapter initialize your listner in constructor like this
mListener = (Listener) context;
In your bindViewHolder method
holder.yourView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.performOperation(position);
}
});
Now in your Activity implement that interface like this
public class LegacyHomeActivity extends ActivityBaseDrawer implements listner {
#Override
public void performOperation(int Position) {
//Do whatever you want to do with this position
}
}

Your interface adapter class should be like this
public class LegacyModeHomeAdapter extends RecyclerView.Adapter<LegacyModeHomeAdapter.ItemViewHolder> {
private List<Video> videoList;
private Context mContext;
public static LegacyVideoClickListener onVideosRVItemClickListener;
private LayoutInflater getLayoutInflater() {
return LayoutInflater.from(mContext);
}
public LegacyModeHomeAdapter(Context mContext, LegacyVideoClickListener onVideosRVItemClickListener) {
this.mContext = mContext;
this.onVideosRVItemClickListener = onVideosRVItemClickListener;
}
public void setVideos(List<Video> videosList) {
this.videoList = videosList;
notifyDataSetChanged();
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.layout_legacy_mode_home_video_item, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
Video video = videoList.get(position);
Picasso.with(mContext).load(video.getThumb()).into(holder.categoryImage);
holder.categoryName.setText(video.getTitle());
holder.title_image_btn.setText(video.getDisplayType());
holder.VideosItemClickListener(position, onVideosRVItemClickListener);
}
#Override
public int getItemCount() {
if (videoList != null) {
return videoList.size();
}
return 0;
}
public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView categoryName;
private ImageView categoryImage;
private Button title_image_btn;
public ItemViewHolder(View itemView) {
super(itemView);
categoryName = (TextView) itemView.findViewById(R.id.categoryName);
categoryImage = (ImageView) itemView.findViewById(R.id.categoryImage);
title_image_btn = (Button) itemView.findViewById(R.id.title_image_btn);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onVideosRVItemClickListener.onItemClickListener(getPosition(), v);
}
}
public void setOnItemClickListener(LegacyVideoClickListener clickListener) {
LegacyModeHomeAdapter.onVideosRVItemClickListener = clickListener;
}
public interface LegacyVideoClickListener {
public void onItemClickListener(int position, View v);
}
}
And your adapter usage class should be like this
adapter.setOnItemClickListener(new LegacyModeHomeAdapter.LegacyVideoClickListener() {
#Override
public void onItemClick(int position, View v) {
//Your code
}
});
Using this way of interface settings you can achieve the onclick listener function exactly.
Please let me know if you are having trouble still.

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Button btMyButton;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// your implementation. In order to get position you can use `getAdapterPosition()` method
}
}

#Override
public void onBindViewHolder(RecyclerViewAdapter.ItemViewHolder holder, int position) {
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
Try like this

Related

How to initialize right TextView in RecyclerView Adapter class?

I want to set the text of a custom build popup.
As soon as I want to set the text, the classic NullPointerException comes. How can I access the text field in my custom popup? How can I change the text of the TextView order_overview_number.setText(...).
How do I have to properly initialize this? TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
this is Unfortunately wrong...
public class UserBestellAdapter extends RecyclerView.Adapter<UserBestellAdapter.ViewHolder> {
ArrayList<Bestellung> bestellung;
Context mContext;
Dialog epicDialog;
public UserBestellAdapter(Context context, ArrayList<Bestellung> list) {
mContext = context;
bestellung = list;
epicDialog = new Dialog(mContext);
}
#NonNull
#Override
public UserBestellAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.adapter_bestell, parent, false);
UserBestellAdapter.ViewHolder viewHolder = new UserBestellAdapter.ViewHolder(view);
return viewHolder;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull UserBestellAdapter.ViewHolder holder, final int position) {
//Gesamtpreis: holder.item_betrag.setText(String.valueOf(bestellung.get(position).getBetrag()));
// Datum: holder.item_datum.setText(bestellung.get(position).getDatum());
holder.item_items.setText(bestellung.get(position).getProdukte());
//holder.item_code.setText(bestellung.get(position).getBestellnummer());
String bestellid =bestellung.get(position).getBestellnummer() + "";
holder.item_code.setText(bestellid);
holder.item_betrag.setText(Double.toString(bestellung.get(position).getSumme()));
holder.item_datum.setText(bestellung.get(position).getDatum());
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
//order_overview_number.setText();
epicDialog.setContentView(R.layout.user_popup_order_overview);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button btn_order_overview_finish = (Button) epicDialog.findViewById(R.id.btn_order_overview_finish);
System.out.println(bestellung.get(position).getBestellnummer());
// HERE IS THE ERROR :(
//order_overview_number.setText(String.valueOf(bestellung.get(position).getDatum()));
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.show();
}
});
}
#Override
public int getItemCount() {
return bestellung.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_items, item_betrag, item_datum, item_code;
private ConstraintLayout layout_user_bestellung;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_items = itemView.findViewById(R.id.items);
item_betrag = itemView.findViewById(R.id.betrag);
item_datum = itemView.findViewById(R.id.datum);
item_code = itemView.findViewById(R.id.code);
layout_user_bestellung = itemView.findViewById(R.id.layout_user_bestellung);
}
}
}
EDIT (didn't work)
I tried to set the text via itemView like the epicDialog.
#Override
public int getItemCount() {
return bestellung.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_items, item_betrag, item_datum, item_code;
private ConstraintLayout layout_user_bestellung;
private TextView tw;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_items = itemView.findViewById(R.id.items);
item_betrag = itemView.findViewById(R.id.betrag);
item_datum = itemView.findViewById(R.id.datum);
item_code = itemView.findViewById(R.id.code);
layout_user_bestellung = itemView.findViewById(R.id.layout_user_bestellung);
tw = itemView.findViewById(R.id.order_overview_number);
}
}
#Override
public void onBindViewHolder(#NonNull UserBestellAdapter.ViewHolder holder, final int position) {
//Gesamtpreis: holder.item_betrag.setText(String.valueOf(bestellung.get(position).getBetrag()));
// Datum: holder.item_datum.setText(bestellung.get(position).getDatum());
holder.item_items.setText(bestellung.get(position).getProdukte());
//holder.item_code.setText(bestellung.get(position).getBestellnummer());
String bestellid =bestellung.get(position).getBestellnummer() + "";
holder.item_code.setText(bestellid);
holder.item_betrag.setText(Double.toString(bestellung.get(position).getSumme()));
holder.item_datum.setText(bestellung.get(position).getDatum());
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
//order_overview_number.setText();
epicDialog.setContentView(R.layout.user_popup_order_overview);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button btn_order_overview_finish = (Button) epicDialog.findViewById(R.id.btn_order_overview_finish);
System.out.println(bestellung.get(position).getBestellnummer());
holder.tw.setText("hallo");
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.show();
}
});
}
Try
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View v = View.inflate(mContext, R.layout.user_popup_order_overview, null);
EditText order_overview_number = (EditText) v.findViewById(R.id.order_overview_number);
order_overview_number.setText(String.valueOf(bestellung.get(position).getDatum()));
Button btn_order_overview_finish = (Button) v.findViewById(R.id.btn_order_overview_finish);
System.out.println(bestellung.get(position).getBestellnummer());
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.setContentView(v);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
epicDialog.show();
}
});

How to highlight a selected RecyclerView item and use its values in Activity

I have a list of words with translations in RecyclerView. I want the selected word to be highlighted, but at the same time I could use these values in Activity. I can highlight selected values or use the values of a selected item, but the combination of the both fails.
Please, maybe You see where I am wrong and can help solve my problem.
p.s. Please don’t judge me for the not enough clean code and my English, I’m learning. :)
MyListActivity.java
public class MyListActivity extends AppCompatActivity {
public ArrayList<MyWord> myWordList = new ArrayList<>();
SelectData sd = new SelectData();
int wordId;
String word;
String translation;
public RecyclerView mRecycleView;
public MyAdapter mAdapter;
public RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_list);
sd.selectMyWords(myWordList);
buildRecycleView();
Button btnInsert = findViewById(R.id.mywords_button_insert);
Button btnEdit = findViewById(R.id.mywords_button_edit);
Button btnDelete = findViewById(R.id.mywords_button_delete);
Button btnMain = findViewById(R.id.mywords_button_backttomain);
mAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// **This is my selected item values**
wordId = myWordList.get(position).getWordId();
word = myWordList.get(position).getWord();
translation = myWordList.get(position).getTranslation();
Toast.makeText(MyListActivity.this, "Selected -> " + word, Toast.LENGTH_SHORT).show();
}
});
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(word == null)) {
Intent intentInsert = new Intent(MyListActivity.this, InsertActivity.class);
intentInsert.putExtra("W", word);
intentInsert.putExtra("TR", translation);
intentInsert.putExtra("ACTION", "ED");
startActivity(intentInsert);
} else {
Toast.makeText(MyListActivity.this, "Select word", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void buildRecycleView(){
mRecycleView = findViewById(R.id.mywords_RecycleView);
mRecycleView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MyAdapter(myWordList);
mRecycleView.setLayoutManager(mLayoutManager);
mRecycleView.setAdapter(mAdapter);
if (myWordList.isEmpty()){
Toast.makeText(this, "word list is empty", Toast.LENGTH_SHORT).show();
}
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<MyWord> mMyWordList;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewEN;
public TextView mTextViewLT;
public ImageView imageViewLearned;
public MyViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextViewEN = itemView.findViewById(R.id.myList_textView_word);
mTextViewLT = itemView.findViewById(R.id.myList_textView_translation);
imageViewLearned = itemView.findViewById(R.id.iV_learned);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public MyAdapter(ArrayList<MyWord> myWordList){
mMyWordList = myWordList;
}
int selectedItem = -1;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_view_layout, parent, false);
MyViewHolder mvh = new MyViewHolder(v, mListener);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
MyWord currentMyWord = mMyWordList.get(position);
holder.mTextViewEN.setText(currentMyWord.getWord());
holder.mTextViewLT.setText(currentMyWord.getTranslation());
// TODO - START (select item highlight) - if I activate highlighting, the assignment of values no longer works in MyListActivity.
/* holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = position;
notifyDataSetChanged();
}
});
if (selectedItem == position) {
holder.itemView.setBackgroundColor(Color.parseColor("#C0C0C0"));
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
} */
//TODO -END
}
#Override
public int getItemCount() {
return mMyWordList.size();
}
}
Looks like your commented code would overwrite your click listener with one that only hightlights. Try combining them:
public MyViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextViewEN = itemView.findViewById(R.id.myList_textView_word);
mTextViewLT = itemView.findViewById(R.id.myList_textView_translation);
imageViewLearned = itemView.findViewById(R.id.iV_learned);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
selectedItem = position;
notifyDataSetChanged();
listener.onItemClick(position);
}
}
}
});
}

How can I get a variable from RecyclerView Adapter passed to MainActivity?

I was just playing around with some code, learning new things, when I ran into this problem... I'm trying to pass a variable from my RecylcerViewAdapter to a method in MainActivity, but I just can't seem to accomplish it.
I tried a lot of different thing with interfaces and casting, but nothing did the trick. Since I'm fairly new to all of this, maybe I'm making a trivial mistake somewhere?
My Interface:
public interface AdapterCallback {
void onMethodCallback(int id);
}
This is my adapter class:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private List<Post> postList;
private Context context;
private AdapterCallback listener;
public PostAdapter() {
}
public PostAdapter(List<Post> postList, Context context) {
this.postList = postList;
this.context = context;
}
public void setListener(AdapterCallback listener) {
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.tvTitle.setText(postList.get(position).getTitle());
viewHolder.tvBody.setText(new StringBuilder(postList.get(position).getBody().substring(0, 20)).append("..."));
viewHolder.tvId.setText(String.valueOf(postList.get(position).getUserId()));
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = postList.get(position).getId();
if (listener != null) {
listener.onMethodCallback(id);
}
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvBody;
TextView tvId;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvBody = itemView.findViewById(R.id.tvBody);
tvId = itemView.findViewById(R.id.tvId);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
And my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivityLog";
private CompositeDisposable disposable = new CompositeDisposable();
#BindView(R.id.rvPosts)
RecyclerView rvPosts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
rvPosts.setHasFixedSize(true);
rvPosts.setLayoutManager(new LinearLayoutManager(this));
populateList();
logItems();
}
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
}
});
}
public void logItems() {
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
The populateList() method works just fine, but the logItems() method is the problem.
So when i click on a view in RecyclerView I expect the log to output the title, description and ID of the post that was clicked. nut nothing happens...
So, any help would be appreciated.
Make adapter global variable i.e. a field. Use the same object to set every properties.
private PostAdapter adapter;
Replace your logItems method with this:
public void logItems() {
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
And populateList with this:
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
logItems();
}
});
}
And don't call logItems() from onCreate
This is how I implement with my ListAdapters:
public class FeedbackListAdapter extends RecyclerView.Adapter<FeedbackListAdapter.ViewHolder> {
private final ArrayList<Feedback> feedbacks;
private View.OnClickListener onItemClickListener;
private View.OnLongClickListener onItemLongClickListener;
private final Context context;
public FeedbackListAdapter(ArrayList<Feedback> feedbacks, Context context) {
this.feedbacks = feedbacks;
this.context = context;
}
public void setItemClickListener(View.OnClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(View.OnLongClickListener onItemLongClickListener){
this.onItemLongClickListener = onItemLongClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder{
final TextView feedback, created, updated;
final LinearLayout mainLayout;
ViewHolder(View iv) {
super(iv);
/*
* Associate layout elements to Java declarations
* */
mainLayout = iv.findViewById(R.id.main_layout);
feedback = iv.findViewById(R.id.feedback);
created = iv.findViewById(R.id.created_string);
updated = iv.findViewById(R.id.updated_string);
}
}
#Override
public int getItemCount() {
return feedbacks.size();
}
#Override
#NonNull
public FeedbackListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_feedback_table_row, parent, false);
return new FeedbackListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final #NonNull FeedbackListAdapter.ViewHolder holder, final int position) {
/*
* Bind data to layout
* */
try{
Feedback feedback = feedbacks.get(position);
holder.feedback.setText(feedback.getContent());
holder.created.setText(feedback.getCreated());
holder.updated.setText(feedback.getUpdated());
holder.mainLayout.setOnClickListener(this.onItemClickListener);
holder.mainLayout.setOnLongClickListener(this.onItemLongClickListener);
holder.mainLayout.setTag(feedback.getDbID());
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
holder.mainLayout.setBackgroundResource(outValue.resourceId);
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
In onPopulateList you create an adaptor:
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
However in public void logItems() { you used a different adapter
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
Therefore the list is being populated with 1 adapter, but you are setting the listener on an unused second adapter.
The fix is to use the same adapter for both. If you make the adapater a field, and don't create a new one inside of logItems, but just set your listener it should work.
i.e.
// as a field in your class
private PostAdapter adapter;
then
// in `populateList()`
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
and
// in `logItems()`
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
In Adapter
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListAdapter.OrderItemViewHolder> {
private Context mCtx;
ProgressDialog progressDialog;
//we are storing all the products in a list
private List<CustomerModel> customeritemList;
public CustomerListAdapter(Context mCtx, List<CustomerModel> orderitemList) {
this.mCtx = mCtx;
this.customeritemList = orderitemList;
progressDialog = new ProgressDialog(mCtx);
}
#NonNull
#Override
public OrderItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.activity_customer_list, null);
return new OrderItemViewHolder(view, mCtx, customeritemList);
}
#Override
public void onBindViewHolder(#NonNull OrderItemViewHolder holder, int position) {
CustomerModel customer = customeritemList.get(position);
try {
//holder.textViewPINo.setText("PINo \n"+Integer.toString( order.getPINo()));
holder.c_name.setText(customer.getCustomerName());
holder.c_address.setText(customer.getAddress());
holder.c_contact.setText(customer.getMobile());
holder.i_name.setText(customer.getInteriorName());
holder.i_contact.setText(customer.getInteriorMobile());
holder.i_address.setText(customer.getAddress());
} catch (Exception E) {
E.printStackTrace();
}
}
#Override
public int getItemCount() {
return customeritemList.size();
}
class OrderItemViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
AlertDialog.Builder alert;
private Context mCtx;
TextView c_name, c_contact, c_address, i_name, i_contact, i_address;
TextView OrderItemID, MaterialType, Price2, Qty, AQty;
//we are storing all the products in a list
private List<CustomerModel> orderitemList;
public OrderItemViewHolder(View itemView, Context mCtx, List<CustomerModel> orderitemList) {
super(itemView);
this.mCtx = mCtx;
this.orderitemList = orderitemList;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
// CatelogOrderDetailModel catelogOrderDetailModel = new CatelogOrderDetailModel();
c_name = itemView.findViewById(R.id.customerName);
c_contact = itemView.findViewById(R.id.contact);
c_address = itemView.findViewById(R.id.address);
i_name = itemView.findViewById(R.id.interiorName);
i_address = itemView.findViewById(R.id.interiorAddress);
i_contact = itemView.findViewById(R.id.interiorContact);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
}
#Override
public boolean onLongClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
if (v.getId() == itemView.getId()) {
// showUpdateDeleteDialog(order);
try {
} catch (Exception E) {
E.printStackTrace();
}
Toast.makeText(mCtx, "lc: ", Toast.LENGTH_SHORT).show();
}
return true;
}
}
}

How to recover data according to type (video, text, image) with Firebase Database and different ViewHolders?

I want to retrieve data from my Database to a recyclerview with multiples layout. How to retrieve contents respectively according to whether it is picture or video?
I mean I don't want to give a position to my getItemView like if image == 1 to do this.
I want to retrieve different types of contents in in their particular layouts.
Ex: Like Facebook, if someone post a video and another person post a text they will be shown while scrolling.
Fragment
public class Discover extends Fragment {
private DatabaseReference mDatabaseRefAll;
private RecyclerView recyclerViewDiscover;
DiscoverRecyclerViewAdapter discoverRecyclerViewAdapter;
private ArrayList<Object> discoverItems = new ArrayList<Object>();
private ArrayList<discoverModell> objects = new ArrayList<>();
public Discover() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_discover, container, false);
recyclerViewDiscover = (RecyclerView) view.findViewById(R.id.rcDiscover);
recyclerViewDiscover.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewDiscover.setHasFixedSize(true);
discoverRecyclerViewAdapter = new DiscoverRecyclerViewAdapter(getContext(), discoverItems, objects);
// set adapter
recyclerViewDiscover.setAdapter(discoverRecyclerViewAdapter);
recyclerViewDiscover.setItemAnimator(new DefaultItemAnimator());
return view;
}
private void loadPost() {
// loading the posts
mDatabaseRefAll = FirebaseDatabase.getInstance().getReference("Testing");
Query queryDiscover = mDatabaseRefAll;
queryDiscover.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
Post post = dataSnapshot.getValue(Post.class);
discoverItems.add(post);
discoverRecyclerViewAdapter.notifyDataSetChanged();
// recyclerViewDiscover.scrollToPosition( discoverItems.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
The Adapter
public class DiscoverRecyclerViewAdapter extends RecyclerView.Adapter<DiscoverRecyclerViewAdapter.DiscoverViewHolder> {
private Context ctx;
private ArrayList<Object> arrayListDiscoverContent;
private ArrayList<Object> horizontalContent;
private ArrayList<discoverModell> arraydiscoverRow;
private static final int LAYOUT_ADS = 1;
private static int LAYOUT_DISCOVERROW = 0;
private static int LAYOUT_DISCOVERCONTENT = 2;
public DiscoverRecyclerViewAdapter(Context context, ArrayList<Object> arrayListDiscoverContent, ArrayList<discoverModell> arraydiscoverRow) {
this.ctx = context;
this.arrayListDiscoverContent = arrayListDiscoverContent;
this.arraydiscoverRow = arraydiscoverRow;
}
#Override
public DiscoverViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ctx = parent.getContext();
if (viewType == LAYOUT_ADS){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_banner_view, parent, false);
return new DiscoverViewHolder(view);
}
if (viewType == LAYOUT_DISCOVERROW) {
View goToContent = LayoutInflater.from(parent.getContext()).inflate(R.layout.discover_by_content, parent, false);
return new DiscoverViewHolder(goToContent);
} else if (viewType == LAYOUT_DISCOVERCONTENT) {
View videoView = LayoutInflater.from(parent.getContext()).inflate(R.layout.pmc_video_row, parent, false);
return new DiscoverViewHolder(videoView);
}
return null;
}
#Override
public void onBindViewHolder(DiscoverViewHolder holder, int position) {
//String type = arrayListDiscoverContent.get(position).getType();
if (getItemViewType(position) == LAYOUT_ADS){
DiscoverViewHolder.adsDiscoverView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ctx, google_ads_video.class);
ctx.startActivity(intent);
}
});
} else if (getItemViewType(position) == LAYOUT_DISCOVERROW) {
final discoverModell discoverM = (discoverModell) arraydiscoverRow.get(position);
DiscoverViewHolder.obooks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent booksIntent = new Intent(ctx, menu_book.class);
ctx.startActivity(booksIntent);
}
});
DiscoverViewHolder.olisticles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent listIntent = new Intent(ctx, menu_listicle.class);
ctx.startActivity(listIntent);
}
});
DiscoverViewHolder.oinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent odatingIntent = new Intent(ctx, Buildinginfo.class);
ctx.startActivity(odatingIntent);
}
});
}
}
public static class DiscoverViewHolder extends RecyclerView.ViewHolder {
public static View adsDiscoverView, gotobannerview;
public static Context ctx;
public static TextView name_discover, autordiscover;
PublisherAdView mPublisherAdView;
public DiscoverViewHolder(View itemView) {
super(itemView);
this.ctx = ctx;
gotobannerview = itemView;
name_discover = itemView.findViewById(R.id.textView19);
autordiscover = itemView.findViewById(R.id.autorId);
}
}
public static class DiscoverRowViewHolder extends RecyclerView.ViewHolder {
public static Context ctx;
public static View adsDiscoverView;
public static ImageView obooks, olisticles, oinfo;
public DiscoverRowViewHolder(View itemView) {
super(itemView);
this.ctx = ctx;
adsDiscoverView = itemView;
obooks = (ImageView) itemView.findViewById(R.id.obooks);
olisticles = (ImageView) itemView.findViewById(R.id.olisticles);
oinfo = (ImageView) itemView.findViewById(R.id.oinfo);
}
}
#Override
public int getItemCount() {
return arrayListDiscoverContent.size();
}
#Override
public int getItemViewType(int position) {
if (position == 0){
return LAYOUT_DISCOVERROW;
} else if (position == 1){
return LAYOUT_ADS;
}
return LAYOUT_DISCOVERCONTENT;
}

Error in recyclerView

Can anyone check if there are errors in it. here my code, If there is any error in the code please tell me? I don't know how to fix the code Search.java.
in my RecyclerItemClickListener.java
public interface RecyclerItemClickListener {
void onItemClick(int position);
}
My Adapter HierAdapter.java
public class HireAdapter extends RecyclerView.Adapter<HireAdapter.ViewHolder>{
private ArrayList<HireItem> TeacherItemList;
private Context context;
private RecyclerItemClickListener itemClickListener;
public HireAdapter(Context c, ArrayList<HireItem> teacherItemList, RecyclerItemClickListener listener) {
TeacherItemList = teacherItemList;
context = c;
itemClickListener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public final TextView nameText, subjectText,levelText ,cityText;
public ViewHolder(View itemView) {
super(itemView);
nameText = (TextView)itemView.findViewById(R.id.result_name);
subjectText = (TextView)itemView.findViewById(R.id.result_subject);
levelText = (TextView)itemView.findViewById(R.id.result_level);
cityText = (TextView)itemView.findViewById(R.id.result_city);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return TeacherItemList.size();
}}
Here Search.java, I wrote notes at each error. Because I did not know how to correct some codes to work with HireAdapter and RecyclerItemClickListener, can anyone solve the error?
public class Search extends Fragment implements RecyclerItemClickListener {
private Context context;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private List<HireItem> hireItem = new ArrayList<>();
HireAdapter mAdapter;
ImageView bt_search;
ProgressDialog progressDialog;
Spinner spinner_sort;
String key = "req_skill1";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_search,container,false);
//Getting FireBase Instance
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("teachers");
//Getting id of Views
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_places);
recyclerView.setAdapter(mAdapter);
//
bt_search = (ImageView)view.findViewById(R.id.bt_search);
spinner_sort = (Spinner)view.findViewById(R.id.spinner_sort);
setupSpinner();
List<HireItem> hireItem = new ArrayList<>();
mAdapter = new HireAdapter(getContext(),R.layout.list_item_teachers,hireItem); // error at (getContext(),R.layout.list_item_teachers,hireItem)
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAdapter != null){
mAdapter.clear(); // error at .clear();
}
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Searching Teachers");
progressDialog.show();
FirebaseDatabase.getInstance().getReference("teachers").orderByChild("subject").startAt(key).endAt(key + "~")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Teachers child = dataSnapshot.getValue(Teachers.class);
HireItem hireItem = new HireItem(child.teaname, child.city, child.subject, child.level, child.sex,child.mobile, child.qualification, child.skill1, child.experince, child.salary,child.age);
mAdapter.add(hireItem); // error at .add
progressDialog.dismiss();
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
else{
recyclerView.setAdapter(mAdapter); // error at recyclerView
}
}
});
return view;
}
private void setupSpinner(){
ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(),R.array.array_teacher_sort,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_sort.setAdapter(adapter);
spinner_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
key = (String)adapterView.getItemAtPosition(i);
if(key.equals(getString(R.string.sort_A))){
key = "Math";
}else if(key.equals(getString(R.string.sort_AA))){
key = "computer";
}
else if(key.equals(getString(R.string.sort_AB))){
key = "Biology";
}
else if(key.equals(getString(R.string.sort_AD))){
key = "Physics";
}
else if(key.equals(getString(R.string.sort_AXX))){
key = "Holy Quran";
}
else if(key.equals(getString(R.string.sort_AZ))){
key = "Chysics";
}
else if(key.equals(getString(R.string.sort_AS))){
key = "English";
}
else if(key.equals(getString(R.string.sort_AQ))){
key = "Arabic";
}
else if(key.equals(getString(R.string.sort_ADD))){
key = "Science";
}
else if(key.equals(getString(R.string.sort_AE))){
key = "History";
}
else if(key.equals(getString(R.string.sort_AW))){
key = "Geograpghy";
}
else if(key.equals(getString(R.string.sort_AR))){
key = "Art education";
}
else if(key.equals(getString(R.string.sort_AT))){
key = "Family education";
}
else if(key.equals(getString(R.string.sort_aae))){
key = "Religion";
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onResume() {
super.onResume();
mAdapter.clear(); // error at .clear();
}
#Override
public void onItemClick(int position) {
} }
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
Here you are setting onClickListner on the same view twice. The Listener set in the onBindViewHolder will override the Listner set in the onCreateViewHolder method.

Categories

Resources