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.
Related
i want to click in my recyclerview and open a new activity to show the datails. Ultil now i
have accomplished to open the activity and show the values "interno" and "siniiga" with the next intent. how can i get "madre and padre" values from firebase? applying the method to add father and mother, then I will use it for the rest of the values that the xml shows. excuse my horrible code. if someone know a different method, let me know
attached code and images.
Main Activity
RecyclerView rv;
List<cow> vacas;
adapter adapter;
ImageButton mbuttoninf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.recyclerViewGirdView);
rv.setLayoutManager(new LinearLayoutManager(this));
vacas = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new adapter(vacas);
rv.setAdapter(adapter);
database.getReference("Vacas").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
vacas.removeAll(vacas);
for (DataSnapshot snapshot1 :
snapshot.getChildren()) {
cow vaca = snapshot1.getValue(cow.class);
vacas.add(vaca);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
cow
String interno;
String siniiga;
String ulr;
String madre;
String padre;
public cow() {
}
public cow(String interno, String siniiga, String ulr, String madre, String padre) {
this.interno = interno;
this.siniiga = siniiga;
this.ulr = ulr;
this.madre = madre;
this.padre = padre;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
public String getSiniiga() {
return siniiga;
}
public void setSiniiga(String siniiga) {
this.siniiga = siniiga;
}
public String getUlr() {
return ulr;
}
public void setUlr(String ulr) {
this.ulr = ulr;
}
public String getMadre() {
return madre;
}
public void setMadre(String madre) {
this.madre = madre;
}
public String getPadre() {
return padre;
}
public void setPadre(String padre) {
this.padre = padre;
}
}
Adapter
List<cow> vacas;
Context context;
public adapter(List<cow> vacas) {
this.vacas = vacas;
}
#NonNull
#Override
public cowviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaca,parent,false);
cowviewHolder holder = new cowviewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final cowviewHolder holder, final int position) {
final cow vacaslist = vacas.get(position);
holder.textViewinterno.setText(String.valueOf(vacaslist.interno));
holder.textViewsiniiga.setText(String.valueOf(vacaslist.siniiga));
Glide.with(holder.imageviewrec.getContext()).load(vacaslist.getUlr()).into(holder.imageviewrec);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(v.getContext(),detailactivity.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return vacas.size();
}
public static class cowviewHolder extends RecyclerView.ViewHolder {
TextView textViewinterno, textViewsiniiga, tvmadre, tvpadre;
ImageView imageviewrec;
public cowviewHolder(#NonNull View itemView) {
super(itemView);
textViewinterno = itemView.findViewById(R.id.interno);
textViewsiniiga = itemView.findViewById(R.id.siniiga);
imageviewrec = itemView.findViewById(R.id.imgrec);
tvmadre = itemView.findViewById(R.id.tvmadre);
tvpadre = itemView.findViewById(R.id.tvpadre);
}
}
detailsactivity
TextView textView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.informationfire);
TextView tvinterno = (TextView) findViewById(R.id.tvinterno);
TextView tvsiniiga = (TextView) findViewById(R.id.tvsiniiga);
String vinterno = "";
String vsiniiga = "";
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
}
}
firebase
enter image description here
and the xml for details
enter image description here
when you are getting data from firebase you saving that data in a Object and then add that object to list, so your list contains objects , so you can pass through the intents same way as you are doing others.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(v.getContext(),detailactivity.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
intent.putExtra("madre", vacaslist.getMadre());
intent.putExtra("padre", vacaslist.getPadre());
v.getContext().startActivity(intent);
}
});
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);
}
}
}
});
}
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();
}
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;
}
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