Android Studio Recycler View Remove Item [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Android Studio Delete Items from Recycler View and List [duplicate]
(2 answers)
Closed 2 years ago.
I am trying to remove Items from my recycler view. Every time I click on an item in my recycler view it provides me with this error.
java.lang.NullPointerException: Attempt to invoke virtual method 'void uk.edu.le.co2103.myrecipebook.RecipeListAdapter.removeItem(int, java.util.List)' on a null object reference
I have made sure that my list has been initalized and used a log to ensure that both position and the list have values in them.
List: [uk.edu.le.co2103.myrecipebook.Recipe#f4d5298, uk.edu.le.co2103.myrecipebook.Recipe#ca6aaf1]
D/MAIN ACTIVITY: Index: 0
Here is my Main Activity code
public class MainActivity extends AppCompatActivity implements
RecipeListAdapter.OnItemClickListener {
private static final String TAG = "MAIN ACTIVITY";
private static final int RESULT_UPDATED = 300;
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
Menu menu;
List<Recipe> recipesList = new ArrayList<>();
ListView search_items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
RecipeListAdapter mAdapter = new RecipeListAdapter(this);
recyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
Log.d(TAG, "SIZE OF LIST: "+ recipesList);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
int size = mAdapter.getItemCount();
Log.d(TAG, "List of List : " + recipes);
recipesList= recipes;
mAdapter.setWords(recipes);
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddRecipeActivity.class);
startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> rData = data.getStringArrayListExtra(AddRecipeActivity.EXTRA_REPLY);
String name = rData.get(0);
String ingredients = rData.get(1);
String method = rData.get(2);
Recipe recipe = new Recipe(name, ingredients, method);
RecipeViewModel.insert(recipe);
}
else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onItemClick(int position, View view) {
Log.d(TAG, "onItemClick Position: " + position);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
recipesList.get(position); //clicked item
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipesList.get(position).getName()); //
update.putExtra("Ingredients", recipesList.get(position).getIngredients());
update.putExtra("Method", recipesList.get(position).getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
Log.d(TAG, "List: " + recipesList);
Log.d(TAG, "Index: " + position);
int removeIndex = position;
recipesList.remove(removeIndex);
}
});
alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
}
Here is my adapter code
public class RecipeListAdapter extends
RecyclerView.Adapter<RecipeListAdapter.RecipeViewHolder> {
private static final String TAG = "ADAPTER";
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position, View view);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position, v);
}
}
}
});
}
#Override
public void onClick(View view) {
mListener.onItemClick(getAdapterPosition(), view);
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
public void deleteItem(final int position) {
mRecipes.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Here is the full error output
2020-04-02 15:27:30.553 5522-5522/uk.edu.le.co2103.myrecipebook E/AndroidRuntime: FATAL EXCEPTION: main
Process: uk.edu.le.co2103.myrecipebook, PID: 5522
java.lang.NullPointerException: Attempt to invoke virtual method 'void uk.edu.le.co2103.myrecipebook.RecipeListAdapter.deleteItem(int)' on a null object reference
at uk.edu.le.co2103.myrecipebook.MainActivity$4.onClick(MainActivity.java:133)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7464)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)

I changed your adapter. I found some problems :
public class RecipeListAdapter extends
RecyclerView.Adapter<RecipeListAdapter.RecipeViewHolder> {
private static final String TAG = "ADAPTER";
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position, View view);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position, v);
}
}
}
});
}
#Override
public void onClick(View view) {
mListener.onItemClick(getAdapterPosition(), view);
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
public void deleteItem(final int position) {
mRecipes.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}

you can use it
public void deleteItem(final int position) {
recipeList.remove(position);
notifyDataSetChanged();
}

Related

How to flow Data from One RecyclerView to Another RecyclerView when an item in first RecyclerView is clicked?

Hi, I faced an issue here.. I was creating a chatbot in which user can type a text to send it and also can select a text out of the recommended texts
so I created two RecycleViews
My goal is - when the user selects one of the recommended text, then that text should appear in the Chatting RecycleView
here is my main Activity Class
public class Charts extends AppCompatActivity {
private static final String USER_KEY = "user";
private static final String BOT_KEY = "bot";
RecyclerView chart_recycle,auto_texts;
EditText message_text;
ImageView send_btn,mic_button;
ImageView setting_button;
ChartsAdapter chartsAdapter;
RecyclerView.LayoutManager linearLayout;
ArrayList<ChartModeClass> modeClassesArrayList = new ArrayList<>();
AutoAdapter autoAdapter;
RecyclerView.LayoutManager horizontal;
List<Texts> list = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatting_hole);
message_text = findViewById(R.id.message_text);
send_btn = findViewById(R.id.send_btn);
mic_button = findViewById(R.id.mic_btn);
setting_button = findViewById(R.id.setting_button);
chart_recycle = findViewById(R.id.chart_recycle);
chart_recycle.setHasFixedSize(true);
auto_texts = findViewById(R.id.auto_texts);
auto_texts.setHasFixedSize(true);
linearLayout = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
chart_recycle.setLayoutManager(linearLayout);
//Auto text
horizontal = new LinearLayoutManager(getApplicationContext(),RecyclerView.HORIZONTAL, false);
auto_texts.setLayoutManager(horizontal);
chartsAdapter = new ChartsAdapter(modeClassesArrayList, Charts.this);
chart_recycle.setAdapter(chartsAdapter);
//Auto texts
autoAdapter = new AutoAdapter(getApplicationContext(),list);
auto_texts.setAdapter(autoAdapter);
addInputs();
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(Charts.this);
mic_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.setContentView(R.layout.record);
bottomSheetDialog.show();
}
});
message_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length()==0){
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}else {
send_btn.setVisibility(View.VISIBLE);
mic_button.setVisibility(View.GONE);
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().isEmpty()){
// Toast.makeText(getApplicationContext(),"Enter text",Toast.LENGTH_LONG).show();
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}else {
send_btn.setVisibility(View.VISIBLE);
mic_button.setVisibility(View.GONE);
}
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length()==0){
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}
}
});
send_btn.setOnClickListener(view -> {
if (message_text.getText().toString().isEmpty()) {
Toast.makeText(Charts.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
returnResponse(message_text.getText().toString());
}
message_text.setText("");
});
}
#SuppressLint("NotifyDataSetChanged")
private void returnResponse(String message) {
modeClassesArrayList.add(new ChartModeClass(message, USER_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size()-1);
String url = "http://xxxxxxxxxxxxxxxx"+message;
String BASE_URL = "https://xxxxxxxxx";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);
Call<MessageModeClass> call = retrofitApi.getMessage(url);
call.enqueue(new Callback<MessageModeClass>() {
#Override
public void onResponse(#NonNull Call<MessageModeClass> call, #NonNull Response<MessageModeClass> response) {
if (response.isSuccessful()) {
MessageModeClass messageModeClass = response.body();
if (messageModeClass != null) {
modeClassesArrayList.add(new ChartModeClass(messageModeClass.getCnt(), BOT_KEY));
}
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
} else {
Toast.makeText(Charts.this, "response is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<MessageModeClass> call, #NonNull Throwable t) {
modeClassesArrayList.add(new ChartModeClass("No response check your network connection!", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}
});
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onStart() {
super.onStart();
String lang = getIntent().getExtras().getString("lang");
if (lang.equals("english")){
modeClassesArrayList.add(new ChartModeClass("Hey welcome back am fema bot", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}else if (lang.equals("swahili")){
modeClassesArrayList.add(new ChartModeClass("Habari karibu miminni bot niliyetengenezw", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}else {
modeClassesArrayList.add(new ChartModeClass("Hey welcome back am fema bot", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}
}
private void addInputs() {
Texts text1 = new Texts("gender?");
Texts text2 = new Texts("gender equality");
Texts text3 = new Texts("what is good about females");
Texts text4 = new Texts("un goals");
Texts text5 = new Texts("about men");
list.addAll(Arrays.asList(new Texts[]{text1,text2,text3,text4,text5}));
}
}
here is my Adapter class class codes
public class AutoAdapter extends RecyclerView.Adapter<AutoAdapter.ViewHolderClass> {
Context context;
List<Texts> list;
public AutoAdapter(Context context, List<Texts> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_list,parent,false);
ViewHolderClass viewHolderClass = new ViewHolderClass(view);
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderClass holder, #SuppressLint("RecyclerView") int position) {
holder.input_text.setText(list.get(position).getText());
holder.input_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// my stack
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolderClass extends RecyclerView.ViewHolder {
TextView input_text;
public ViewHolderClass(#NonNull View itemView) {
super(itemView);
input_text = itemView.findViewById(R.id.input_text);
}
}
}
You can add a list of your recommendations in another RecyclerView
Then in the ViewHolder of each item of the RecyclerView add Callback to listen on click events when a user clicks one of the item like the following
public class ViewHolderClass extends RecyclerView.ViewHolder {
private TextView input_text;
private final Callback callback; // custom callback
public ViewHolderClass(#NonNull View itemView, Callback callback) {
super(itemView);
this.callback = callback;
input_text = itemView.findViewById(R.id.input_text);
// now add onClickListener of the itemView to fire custom callback
itemView.setOnClickListener(view -> {
this.callback.onItemClick(getAdapterPosition());
});
}
// this is my custom callback for return click event
public interface Callback {
void onItemClick(int position);
}
}
Now inside your adapter add the callback from viewholder
public class AutoAdapter extends RecyclerView.Adapter<AutoAdapter.ViewHolderClass> {
private Context context;
private List<Texts> list;
private AutoAdapterCallback callback;
public AutoAdapter(Context context, List<Texts> list) {
this.context = context;
this.list = list;
}
public setCallback(AutoAdapterCallback callback) {
this.callback = callback;
}
#NonNull
#Override
public ViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_list,parent,false);
ViewHolderClass viewHolderClass = new ViewHolderClass(view, new ViewHolderClass.Callback() {
#Override
public void onItemClick(int position) {
// forward callback to adapter callback
if (callback != null) {
// get actual item from its position
final Texts texts = getItemByPosition(position);
// send to adapter callback
callback.onItemClick(texts);
}
});
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderClass holder, #SuppressLint("RecyclerView") int position) {
holder.input_text.setText(list.get(position).getText());
// I haven't used this inteady I added callback on viewholder side
// holder.input_text.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// // my stack
// }
// });
}
#Override
public int getItemCount() {
return list.size();
}
// return Texts object by given position
public Texts getItemByPosition(int position) {
return this.list.get(position);
}
// add adapter callback to be called by viewholder
public interface AdapterCallback {
void onItemClick(Texts texts);
}
}
After that, now on your Activity you can easily listen on any item when a user clicks and get its corresponding Texts object from list as following:
//code ...
// here
//Auto texts
autoAdapter = new AutoAdapter(getApplicationContext(),list);
//set callback to listen for click events
autoAdapter.setCallback(new AutoAdapter.AutoAdapterCallback() {
#Override
public void onItemClick(Texts texts) {
// you can get your clicked item here
// now you can put texts object to another RecyclerView :)
}
});
auto_texts.setAdapter(autoAdapter);
//code ...

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 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.

RecyclerVIew onItemClickListener Not working

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

Categories

Resources