This is my RecyclerView Adaptor Class
public class TodoAdaptor extends RecyclerView.Adapter<TodoAdaptor.SingleTodoView> {
private CheckBox checkbox;
private TextView title, dueDate;
private Context context;
private ArrayList<SingleTodo> todoList;
private onItemCLickListener itemCLickListener;
public TodoAdaptor(Context context, ArrayList<SingleTodo> todoList, onItemCLickListener onItemClickListener) {
this.context = context;
this.todoList = todoList;
this.itemCLickListener = onItemClickListener;
}
#NonNull
#Override
public SingleTodoView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_todo, parent, false);
return new SingleTodoView(v, itemCLickListener);
}
#Override
public void onBindViewHolder(#NonNull SingleTodoView holder, int position) {
SingleTodo singleTodo = todoList.get(position);
checkbox.setChecked(singleTodo.isComplete());
title.setText(singleTodo.getTitle());
if (singleTodo.isComplete()) {
title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Toast.makeText(context, "IsCompleted", Toast.LENGTH_SHORT).show();
} else {
title.setPaintFlags(title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
Toast.makeText(context, "Not IsCompleted", Toast.LENGTH_SHORT).show();
}
if (singleTodo.getDueDate().isEmpty()) {
dueDate.setVisibility(View.GONE);
} else {
dueDate.setText(singleTodo.getDueDate());
}
}
#Override
public int getItemCount() {
return todoList.size();
}
class SingleTodoView extends RecyclerView.ViewHolder {
private SingleTodoView(#NonNull View itemView, final onItemCLickListener itemCLickListener) {
super(itemView);
checkbox = itemView.findViewById(R.id.todo_list_completed_checkbox);
title = itemView.findViewById(R.id.todo_list_title);
dueDate = itemView.findViewById(R.id.todo_list_due_date);
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onTextClickListener(getAdapterPosition());
}
});
checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onCheckboxClickListener(getAdapterPosition());
}
});
}
}
public interface onItemCLickListener {
void onTextClickListener(int position);
void onCheckboxClickListener(int position);
}
}
This is My Adaptor
todoAdaptor = new TodoAdaptor(this, singleTodoArrayList, new TodoAdaptor.onItemCLickListener() {
#Override
public void onTextClickListener(int position) {
singleTodo = singleTodoArrayList.get(position);
singleTodo.setTitle("This is Test");
singleTodoArrayList.set(position, singleTodo);
todoAdaptor.notifyItemChanged(position);
}
#Override
public void onCheckboxClickListener(int position) {
singleTodo = singleTodoArrayList.get(position);
singleTodo.setComplete(!singleTodo.isComplete());
singleTodoArrayList.set(position, singleTodo);
todoAdaptor.notifyItemChanged(position);
}
});
and This is my SingleTodo Class
package com.example.simpletodo.classes;
public class SingleTodo {
private int id;
private String title;
private String dueDate;
private boolean isComplete;
public SingleTodo(int id, String title, String dueDate, boolean isComplete) {
this.id = id;
this.title = title;
this.dueDate = dueDate;
this.isComplete = isComplete;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDueDate() {
return dueDate;
}
public boolean isComplete() {
return isComplete;
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
}
Whenever I check the checkbox, Text of that item should paint Strikethrough and Its not working as Expected
I have 3 Items in the list, when i click checkbox Item get Checked and Text Strikethrough works but when i again click checkbox checkbox stay checked (although Object is being Updated as it should be) and strikethrought text revert to normal, and i have to click checkbox twice again for check box to get unchecked
other issue is that when i checked on item and then i try to check other item, Current Item text get replaced by one of the other checked item Text.
Images :
Default:
When i click the Checkbox Once:
When i Click the Checkbox Again:
When i Checked multiple Items one by one(I have not changed position of any item before checking they was in default order and after checking --in order-- this is what i get)
Any Help is Appreciated. I just want my code to work as Expected.
I found the Solution from this Question
I had to change my Adaptor Class. I Declared Views inside my view holder class and onBindViewHolder, i am using first parameter (holder) to get my Views
public class TodoAdaptor extends RecyclerView.Adapter<TodoAdaptor.SingleTodoView> {
private boolean darkTheme;
private Context context;
private ArrayList<SingleTodo> todoList;
private onItemCLickListener itemCLickListener;
public TodoAdaptor(Context context, ArrayList<SingleTodo> todoList, boolean darkTheme, onItemCLickListener onItemClickListener) {
this.darkTheme = darkTheme;
this.context = context;
this.todoList = todoList;
this.itemCLickListener = onItemClickListener;
}
#NonNull
#Override
public SingleTodoView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_todo, parent, false);
return new SingleTodoView(v, itemCLickListener);
}
#Override
public void onBindViewHolder(#NonNull SingleTodoView holder, int position) {
SingleTodo singleTodo = todoList.get(position);
holder.checkbox.setChecked(singleTodo.isComplete());
holder.title.setText(singleTodo.getTitle());
if (singleTodo.isComplete()) {
holder.title.setPaintFlags(holder.title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
holder.title.setPaintFlags(holder.title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
if (singleTodo.getDueDate().isEmpty()) {
holder.dueDate.setVisibility(View.GONE);
} else {
holder.dueDate.setVisibility(View.VISIBLE);
holder.dueDate.setText(singleTodo.getDueDate());
}
}
#Override
public int getItemCount() {
return todoList.size();
}
class SingleTodoView extends RecyclerView.ViewHolder {
private CheckBox checkbox;
private TextView title, dueDate;
private SingleTodoView(#NonNull View itemView, final onItemCLickListener itemCLickListener) {
super(itemView);
checkbox = itemView.findViewById(R.id.todo_list_completed_checkbox);
title = itemView.findViewById(R.id.todo_list_title);
dueDate = itemView.findViewById(R.id.todo_list_due_date);
if (darkTheme) {
title.setTextColor(context.getResources().getColor(R.color.colorLightGray));
dueDate.setTextColor(context.getResources().getColor(R.color.colorLightGray));
} else {
title.setTextColor(context.getResources().getColor(R.color.colorBlack));
dueDate.setTextColor(context.getResources().getColor(R.color.colorBlack));
}
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onTextClickListener(getAdapterPosition());
}
});
checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onCheckboxClickListener(getAdapterPosition());
}
});
}
}
public interface onItemCLickListener {
void onTextClickListener(int position);
void onCheckboxClickListener(int position);
}
}
Related
Idk why is it not working, Im trying to transfer data, i'm doing an app but when i run it i get an error, the Error is in the BlogActivity Class
"showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));"(java.lang.NullPointerException).
This is BlogActivity Class:
public class BlogActivity extends AppCompatActivity{
private static final String EXTRAS_BLOG = "EXTRAS_BLOG";
private TextView textTitle;
private TextView textDate;
private TextView textAuthor;
private TextView textRating;
private TextView textDescription;
private TextView textViews;
private RatingBar ratingBar;
private ImageView imageAvatar;
private ImageView imageMain;
private ImageView imageBack;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogpage);
imageMain = findViewById(R.id.yemenImg);
imageAvatar = findViewById(R.id.yemenAvatar);
imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent myInt = new Intent(getApplicationContext(),MainActivity.class);
startActivity(myInt);
}
},2);
}
});
textDate = findViewById(R.id.dateYemen);
textTitle = findViewById(R.id.textTitle);
textAuthor = findViewById(R.id.yemenAuthor);
textRating = findViewById(R.id.textRating);
textViews = findViewById(R.id.textViews);
textDescription = findViewById(R.id.textDescription);
ratingBar = findViewById(R.id.ratingBar);
progressBar = findViewById(R.id.progressBar);
showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));
}
/*private void loadData()
{
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showData(blogList.get(0));
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
showErrorSnackbar();
}
});
}
});
}*/
private void showData(Blog blog)
{
progressBar.setVisibility(View.GONE);
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
textAuthor.setText(blog.getAuthor().getName());
textRating.setText(String.valueOf(blog.getRating()));
textViews.setText(String.format("(%d views)", blog.getViews()));
textDescription.setText(blog.getDescription());
textDescription.setText(Html.fromHtml(blog.getDescription(),Html.FROM_HTML_MODE_COMPACT));
ratingBar.setRating(blog.getRating());
ratingBar.setVisibility(View.VISIBLE);
imageBack.setImageResource(R.drawable.ic_baseline_arrow_back_24);
Glide.with(this)
.load(blog.getImage())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageMain);
Glide.with(this)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
/*private void showErrorSnackbar()
{
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
snackbar.dismiss();
});
snackbar.show();
}*/
public static void startBlogDetailsActivity(Activity activity, Blog blog) {
Intent intent = new Intent(activity, BlogActivity.class);
intent.putExtra(EXTRAS_BLOG, blog);
activity.startActivity(intent);
}
Blog Class:
public class Blog implements Parcelable {
private String id;
private Author author;
private String title;
private String date;
private String image;
private String description;
private int views;
private float rating;
protected Blog(Parcel in) {
id = in.readString();
title = in.readString();
date = in.readString();
image = in.readString();
description = in.readString();
views = in.readInt();
rating = in.readFloat();
author = in.readParcelable(Author.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(date);
dest.writeString(image);
dest.writeString(description);
dest.writeInt(views);
dest.writeFloat(rating);
dest.writeParcelable(author, 0);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Blog> CREATOR = new Creator<Blog>() {
#Override
public Blog createFromParcel(Parcel in) {
return new Blog(in);
}
#Override
public Blog[] newArray(int size) {
return new Blog[size];
}
};
public String getTitle() {
return title;
}
public String getDate() {
return date;
}
public String getImage() {
return image;
}
public String getDescription() {
return description;
}
public int getViews() {
return views;
}
public float getRating() {
return rating;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Blog blog = (Blog) o;
return views == blog.views &&
Float.compare(blog.rating, rating) == 0 &&
Objects.equals(id, blog.id) &&
Objects.equals(author, blog.author) &&
Objects.equals(title, blog.title) &&
Objects.equals(date, blog.date) &&
Objects.equals(image, blog.image) &&
Objects.equals(description, blog.description);
}
#Override
public int hashCode() {
return Objects.hash(id, author, title, date, image, description, views, rating);
}
This is Main Activity Class:
public class MainActivity extends AppCompatActivity {
private MainAdapter adapter;
private SwipeRefreshLayout refreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainAdapter(blog ->
BlogActivity.startBlogDetailsActivity(this, blog));
RecyclerView recyclerView = findViewById(R.id.recylerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
refreshLayout = findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(this::loadData);
loadData();
}
private void loadData()
{
refreshLayout.setRefreshing(true);
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
adapter.submitList(blogList);
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
showErrorSnackbar();
}
});
}
});
}
private void showErrorSnackbar() {
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
loadData();
snackbar.dismiss();
});
snackbar.show();
}
This is MainAdapter Class:
public class MainAdapter extends ListAdapter<Blog, MainAdapter.MainViewHolder>{
public interface OnItemClickListener{
void onItemClicked(Blog blog);
}
private OnItemClickListener clickListener;
public MainAdapter(OnItemClickListener clickListener){
super(DIFF_CALLBACK);
this.clickListener = clickListener;
}
#NonNull
#Override
public MainAdapter.MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_listlayout,parent,false);
return new MainViewHolder(view, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.MainViewHolder holder, int position)
{
holder.bindTo(getItem(position));
}
static class MainViewHolder extends RecyclerView.ViewHolder
{
private TextView textTitle;
private TextView textDate;
private ImageView imageAvatar;
private Blog blog;
public MainViewHolder(#NonNull View itemView, OnItemClickListener listener)
{
super(itemView);
itemView.setOnClickListener(view -> listener.onItemClicked(blog));
textTitle = itemView.findViewById(R.id.textTitle);
textDate = itemView.findViewById(R.id.textDate);
imageAvatar = itemView.findViewById(R.id.imageAvatar);
}
void bindTo(Blog blog)
{
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
Glide.with(itemView)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
}
private static final DiffUtil.ItemCallback<Blog> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Blog>()
{
#Override
public boolean areItemsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.getId().equals(newItem.getId());
}
#Override
public boolean areContentsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.equals(newItem);
}
};
You may set value to blog variable in MainViewHolder.
Add this line to your bindTo() method body:
this.blog = blog
This is the code for the nested recycler view.
If I add data using the push() method, i get the Nested RecycleView with Firebase this error:
Expected a List while deserializing, but got a class java.util.HashMap
AlertDialog dialog;
IFirebaseLoadListener iFirebaseLoadListener;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myData= FirebaseDatabase.getInstance().getReference("MyData");
dialog= new SpotsDialog.Builder().setContext(this).build();
iFirebaseLoadListener = this;
// view
my_recycler_view= (RecyclerView)findViewById(R.id.my_recycler_view);
my_recycler_view.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
load data
getFirebaseData();
}
private void getFirebaseData() {
dialog.show();
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<itemGroup> itemGroups= new ArrayList<>();
for(DataSnapshot groupSnapshot: dataSnapshot.getChildren())
{
itemGroup itemGroup= new itemGroup();
///
Firebase instance code
///
itemGroup.setHeaderTitle(groupSnapshot.child("headerTitle").getValue(true).toString());
GenericTypeIndicator<ArrayList<itemData>> genericTypeIndicator= new GenericTypeIndicator<ArrayList<itemData>>(){} ;
itemGroup.setListItem(groupSnapshot.child("listItem").child(key).getValue(genericTypeIndicator));
itemGroups.add(itemGroup);
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<itemGroup> itemGroupList) {
MyItemGroupAdapter adapter = new MyItemGroupAdapter(this,itemGroupList);
my_recycler_view.setAdapter(adapter);
dialog.dismiss();
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
public class itemData {
private String name ,image;
public itemData() {
}
public itemData(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
public class itemGroup {
private String headerTitle;
private ArrayList<itemData> listItem;
public itemGroup() {
}
public itemGroup(String headerTitle, ArrayList<itemData> listItem) {
this.headerTitle = headerTitle;
this.listItem = listItem;
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<itemData> getListItem() {
return listItem;
}
public void setListItem(ArrayList<itemData> listItem) {
this.listItem = listItem;
}
}
public class MyItemAdapter extends RecyclerView.Adapter<MyItemAdapter.MyViewHolder> {
private Context context;
private List<itemData> itemDataList;
public MyItemAdapter(Context context, List<itemData> itemDataList) {
this.context = context;
this.itemDataList = itemDataList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView =
LayoutInflater.from(context).inflate(R.layout.layout_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.txt_item_titles.setText(itemDataList.get(i).getName());
Picasso.get().load(itemDataList.get(i).getImage()).into(myViewHolder.img_item);
myViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int i) {
Toast.makeText(context, ""+ itemDataList.get(i).getName(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (itemDataList != null ? itemDataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
TextView txt_item_titles;
ImageView img_item;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public MyViewHolder (View itemView ){
super(itemView);
txt_item_titles= (TextView)itemView.findViewById(R.id.tvTitle);
img_item= (ImageView) itemView.findViewById(R.id.itemImage);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
iItemClickListener.onItemClickListener(v,getAdapterPosition());
}
}
}
public class MyItemGroupAdapter extends
RecyclerView.Adapter<MyItemGroupAdapter.MyViewHolder> {
private Context context;
private List<itemGroup> dataList;
public MyItemGroupAdapter(Context context, List<itemGroup> dataList) {
this.context = context;
this.dataList = dataList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView =
LayoutInflater.from(context).inflate(R.layout.layout_group,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.item_title.setText(dataList.get(i).getHeaderTitle());
List<itemData> itemData = dataList.get(i).getListItem();
MyItemAdapter itemListAdapter=new MyItemAdapter(context,itemData);
myViewHolder.recycler_view_item_list.setHasFixedSize(true);
myViewHolder.recycler_view_item_list.setLayoutManager(new
LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
myViewHolder.recycler_view_item_list.setAdapter(itemListAdapter);
myViewHolder.recycler_view_item_list.setNestedScrollingEnabled(false);
// btn more
myViewHolder.btn_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Button More "+ myViewHolder.item_title.getText(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (dataList != null ? dataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView item_title ;
RecyclerView recycler_view_item_list;
Button btn_more;
public MyViewHolder (View itemView ){
super (itemView);
item_title= (TextView) itemView.findViewById(R.id.itemTitle);
btn_more= (Button)itemView.findViewById(R.id.btMore);
recycler_view_item_list=
(RecyclerView)itemView.findViewById(R.id.recycler_view_list);
}
}
}
This happens when you try to have a structure like this in the database:
"list": {
"-Nasdueqriyew": "First value",
"-Nberqiy39esd": "Second value",
"-Nc3hadsiuhad": "Third value"
}
And then try to map it to a List or array in your Java class.
The JSON structure is not a list, because it was pairs of keys and values, which in Java translates to:
Map<String, Object>
So most likely, the List<itemData> in your code needs to be a Map<String, itemData>.
I need some help with two of my recycler views(one named "recentRecycler", and the other "topPlacesRecycler").My question is, how do I make to be redirected on a specific Activity when I click a specific item from the recycler. For example:
1- when I click the first item from the "recentRecycler" to be redirected to "Parlament.class"
2- when I click the first item from the "topPlacesRecycler" to be redirected to "Ramada.class"
etc.
My Main Activity which is named "BUCint" (The code from the bottom is from a drawerlayout that I use for my project)
public class BUCint extends AppCompatActivity {
DrawerLayout drawerLayout;
RecyclerView recentRecycler, topPlacesRecycler;
RecentsAdapter recentsAdapter;
TopPlacesAdapter topPlacesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buc_int);
drawerLayout = findViewById(R.id.drawer_layout);
List<RecentsData> recentsDataList = new ArrayList<>();
recentsDataList.add(new RecentsData("Palatul Parlamentului","Cladire administrativă","40 lei",R.drawable.palatulparlamentului));
recentsDataList.add(new RecentsData("Arcul de Triumf","Monument istoric","Gratis",R.drawable.arctriumf));
recentsDataList.add(new RecentsData("Carturesti Carusel","Librarie","Gratis",R.drawable.carturesti));
recentsDataList.add(new RecentsData("Parcul Herăstrău","Parc","Gratis",R.drawable.parculherastrau));
recentsDataList.add(new RecentsData("Parcul Cișmigiu","Parc","Gratis",R.drawable.parculcismigiu));
recentsDataList.add(new RecentsData("Muzeul Antipa","Muzeu","20 lei",R.drawable.muzeulantipa));
setRecentRecycler(recentsDataList);
List<TopPlacesData> topPlacesDataList = new ArrayList<>();
topPlacesDataList.add(new TopPlacesData("Ramada Parc","Sectorul 1","227 lei",R.drawable.ramadaparc));
topPlacesDataList.add(new TopPlacesData("Berthelot","Sectorul 1","207 lei",R.drawable.bethelot));
topPlacesDataList.add(new TopPlacesData("Union Plaza","Centru","215 lei",R.drawable.unionplaza));
topPlacesDataList.add(new TopPlacesData("Rin Grande","Sectorul 4","223 lei",R.drawable.ringrande));
topPlacesDataList.add(new TopPlacesData("Hilton Garden","Centru","240 lei",R.drawable.hiltongarden));
setTopPlacesRecycler(topPlacesDataList);
}
private void setRecentRecycler(List<RecentsData> recentsDataList){
recentRecycler = findViewById(R.id.recent_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recentRecycler.setLayoutManager(layoutManager);
recentsAdapter = new RecentsAdapter(this, recentsDataList);
recentRecycler.setAdapter(recentsAdapter);
}
private void setTopPlacesRecycler(List<TopPlacesData> topPlacesDataList){
topPlacesRecycler = findViewById(R.id.top_places_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
topPlacesRecycler.setLayoutManager(layoutManager);
topPlacesAdapter = new TopPlacesAdapter(this, topPlacesDataList);
topPlacesRecycler.setAdapter(topPlacesAdapter);
}
public void ClickMenu(View view){
BUCM.openDrawer(drawerLayout);
}
public void ClickLogo(View view){
BUCM.closeDrawer(drawerLayout);
}
public void ClickHome(View view){
BUCM.redirectActivity(this, Acasa.class);
}
public void ClickLinii(View view){
BUCM.redirectActivity(this,BUClinii.class);
}
public void ClickPreturi(View view){
BUCM.redirectActivity(this, BUCpreturi.class);
}
public void Clickint(View view){
recreate();
}
public void ClickSetari(View view) {
BUCM.redirectActivity(this, Setari.class);
}
public void ClickInformatii(View view){
BUCM.redirectActivity(this, Informatii.class);
}
public void ClickLogout(View view){
BUCM.logout(this);
}
#Override
protected void onPause(){
super.onPause();
BUCM.closeDrawer(drawerLayout);
}
}
The Adapter for recentRecycler, named RecentsAdapter
public class RecentsAdapter extends RecyclerView.Adapter<RecentsAdapter.RecentsViewHolder> {
Context context;
List<RecentsData> recentsDataList;
public RecentsAdapter(Context context, List<RecentsData> recentsDataList) {
this.context = context;
this.recentsDataList = recentsDataList;
}
#NonNull
#Override
public RecentsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recents_row_item, parent, false);
return new RecentsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecentsViewHolder holder, int position) {
holder.countryName.setText(recentsDataList.get(position).getCountryName());
holder.placeName.setText(recentsDataList.get(position).getPlaceName());
holder.price.setText(recentsDataList.get(position).getPrice());
holder.placeImage.setImageResource(recentsDataList.get(position).getImageUrl());
}
#Override
public int getItemCount() {
return recentsDataList.size();
}
public static final class RecentsViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName, countryName, price;
public RecentsViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
}
}
}
The DataModel for recentRecycler, named RecentsData
package com.example.spinner.model;
public class RecentsData {
String placeName;
String countryName;
String price;
Integer imageUrl;
public Integer getImageUrl() {
return imageUrl;
}
public void setImageUrl(Integer imageUrl) {
this.imageUrl = imageUrl;
}
public RecentsData(String placeName, String countryName, String price, Integer imageUrl) {
this.placeName = placeName;
this.countryName = countryName;
this.price = price;
this.imageUrl = imageUrl;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
The Adapter for topPlacesRecycler, named TopPlacesAdapter
public class TopPlacesAdapter extends RecyclerView.Adapter<TopPlacesAdapter.TopPlacesViewHolder> {
Context context;
List<TopPlacesData> topPlacesDataList;
public TopPlacesAdapter(Context context, List<TopPlacesData> topPlacesDataList) {
this.context = context;
this.topPlacesDataList = topPlacesDataList;
}
#NonNull
#Override
public TopPlacesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.top_places_row_item, parent, false);
return new TopPlacesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TopPlacesViewHolder holder, int position) {
holder.countryName.setText(topPlacesDataList.get(position).getCountryName());
holder.placeName.setText(topPlacesDataList.get(position).getPlaceName());
holder.price.setText(topPlacesDataList.get(position).getPrice());
holder.placeImage.setImageResource(topPlacesDataList.get(position).getImageUrl());
}
#Override
public int getItemCount() {
return topPlacesDataList.size();
}
public static final class TopPlacesViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName, countryName, price;
public TopPlacesViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
}
}
}
The DataModel for topPlacesRecycler, named TopPlacesData
public class TopPlacesData {
String placeName;
String countryName;
String price;
Integer imageUrl;
public Integer getImageUrl() {
return imageUrl;
}
public void setImageUrl(Integer imageUrl) {
this.imageUrl = imageUrl;
}
public TopPlacesData(String placeName, String countryName, String price, Integer imageUrl) {
this.placeName = placeName;
this.countryName = countryName;
this.price = price;
this.imageUrl = imageUrl;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
I'm pretty new with Android Studio so every feedback would be gladly accepted.
Thanks in advance!
The best solution that does not overload the adapter would be to use interface.
Declare an interface in your adapter like this...
public class RecentsAdapter extends RecyclerView.Adapter<RecentsAdapter.RecentsViewHolder> {
Context context;
List<RecentsData> recentsDataList;
private RecentsAdapter.OnRecentItemclickListener listener;
public void setOnRecentItemclickListener(RecentsAdapter.OnRecentItemclickListener listener){
this.listener = listener;
}
public RecentsAdapter(Context context, List<RecentsData> recentsDataList) {
this.context = context;
this.recentsDataList = recentsDataList;
}
#NonNull
#Override
public RecentsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recents_row_item, parent, false);
return new RecentsViewHolder(view, listener);
}
#Override
public void onBindViewHolder(#NonNull RecentsViewHolder holder, int position) {
holder.countryName.setText(recentsDataList.get(position).getCountryName());
holder.placeName.setText(recentsDataList.get(position).getPlaceName());
holder.price.setText(recentsDataList.get(position).getPrice());
holder.placeImage.setImageResource(recentsDataList.get(position).getImageUrl());
}
#Override
public int getItemCount() {
return recentsDataList.size();
}
public static final class RecentsViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName, countryName, price;
public RecentsViewHolder(#NonNull View itemView, RecentsAdapter.OnRecentItemclickListener listener) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
itemView.setOnclickListener( -> {
if(listner == null)return;
int pos = getAdapterposition()
if(pos == RecyclerView.NO_POSITION)return;
listner.onRecentItemclickListener(pos);
});
}
}
public interface OnRecentItemclickListener {
void onRecentItemClickListener(int position);
}
}
Add then in you activity
private void setRecentRecycler(List<RecentsData> recentsDataList){
recentRecycler = findViewById(R.id.recent_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recentRecycler.setLayoutManager(layoutManager);
recentsAdapter = new RecentsAdapter(this, recentsDataList);
recentRecycler.setAdapter(recentsAdapter);
recentsAdapter.setOnRecentItemclickListener(this::onOpenParlamentClass)
}
private void onOpenParlamentClass(int position){
//perform your intent here. you can also get the clicked item using the position of the data list and pass it to the receiving activity
}
Happy coding. If you are new to android you can also consider Kotlin.
public static final class RecentsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView placeImage;
TextView placeName, countryName, price;
public RecentsViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = itemView.findViewById(R.id.place_image);
placeName = itemView.findViewById(R.id.place_name);
countryName = itemView.findViewById(R.id.country_name);
price = itemView.findViewById(R.id.price);
itemView.setOnClickListener(this);
//you can do same code for another recyclerview.
}
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Parlament.class);
view.getContext().startActivity(intent);
}
}
I'll use RecyclerView And I've more than 10 items in the list And I Have to change a text color and background layout on a single click of the item and else all the item color not change. Please suggest me the right way to solve this issue. I'll try to change the color in BindViewHolder, ViewHolder and Adapter click item but I'm Successful to change the color but unsuccessful to change the color back.
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
setOnitemclick listener;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
int I=-1;
public class CarTypesHolder extends RecyclerView.ViewHolder {
public CustomTextView mCarType;
public CircleImageView mCarTypeImage;
LinearLayout llRoot;
CardView cardView;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
setOnitemclick listener;
public CarTypesHolder(final View view) {
super(view);
mCarType = (CustomTextView) view.findViewById(R.id.frag_cartypes_inflated_name);
mCarTypeImage = (CircleImageView) view.findViewById(R.id.frag_cartype_inflated_frameImage);
llRoot = (LinearLayout)view.findViewById(R.id.root1);
cardView=(CardView) view.findViewById(R.id.cardf);
}
public void setOnItemClickListner(setOnitemclick listener12) {
listener=listener12;
}
}
public void setOnItemClickListner(setOnitemclick listener12) {
listener=listener12;
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
}
#Override
public CarTypesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.frag_cartype_inflated_view, parent, false);
return new CarTypesHolder(itemView);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder(final CarTypesHolder holder, final int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
I=CarTypesModelsList.get(position).getID();
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.llRoot.setSelected(selectedItems.get(position, false));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(listener);
holder. llRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I=position;
if (I==position)
{
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#00000"));
}
}
});
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
#Override
public long getItemId(int position) {
return CarTypesModelsList.get(position).getID();
}
#Override
public int getItemCount() {
return CarTypesModelsList.size();
}
public void setSelection(LinearLayout imageView,CustomTextView textView,boolean value,int position){
if(value){
imageView.setBackgroundColor(Color.parseColor("#999999"));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
System.out.println("11111111111111111000000111111111111");
imageView.setBackgroundColor(Color.parseColor("#f3f3f3"));
textView.setTextColor(Color.parseColor("#2196F3"));
}
}
public interface setOnitemclick{
void ImageClick(int position, String Name,String Description,int id);
void ImageClickfade(int position, String Name,String Description,int id);
}
#Override
public int getItemViewType(int position) {
return position;
}
}
You can try this,
You'll use to update gradle
maven { url "https://maven.google.com" }
and update the code
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
int I=-1;
public class CarTypesHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CustomTextView mCarType;
public CircleImageView mCarTypeImage;
LinearLayout llRoot;
CardView cardView;
setOnitemclick listener;
public void setOnItemClickListner(setOnitemclick listener)
{
this.listener=listener;
}
public CarTypesHolder(View view) {
super(view);
mCarType = (CustomTextView) view.findViewById(R.id.frag_cartypes_inflated_name);
mCarTypeImage = (CircleImageView) view.findViewById(R.id.frag_cartype_inflated_frameImage);
llRoot = (LinearLayout)view.findViewById(R.id.root1);
cardView=(CardView) view.findViewById(R.id.cardf);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.ImageClick(v,getAdapterPosition());
}
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
}
#Override
public CarTypesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.frag_cartype_inflated_view, parent, false);
return new CarTypesHolder(itemView);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder( final CarTypesHolder holder, int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(new setOnitemclick() {
#Override
public void ImageClick(View v,int position1) {
I=position1;
notifyDataSetChanged();
}
});
if (I==position)
{
System.out.println("11100011111....");
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
System.out.println("11100011111----");
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#2196F3"));
}
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
#Override
public long getItemId(int position) {
return CarTypesModelsList.get(position).getID();
}
#Override
public int getItemCount() {
return CarTypesModelsList.size();
}
public void setSelection(LinearLayout imageView,CustomTextView textView,boolean value,int position){
if(value){
imageView.setBackgroundColor(Color.parseColor("#999999"));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
System.out.println("11111111111111111000000111111111111");
imageView.setBackgroundColor(Color.parseColor("#f3f3f3"));
textView.setTextColor(Color.parseColor("#2196F3"));
}
}
public interface setOnitemclick{
void ImageClick(View view,int position);
}
#Override
public int getItemViewType(int position) {
return position;
}
}
Replace your click like below
public void onBindViewHolder(final CarTypesHolder holder, final int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
I=CarTypesModelsList.get(position).getID();
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.llRoot.setSelected(selectedItems.get(position, false));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(listener);
holder. llRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I=position;
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
notifyDataSetChanged()
}
});
if (I==position)
{
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#00000"));
}
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
This is a part java file which has the function loadMenu and when the corresponding intent opens, the app closes unexpectedly.
private void loadMenu() {
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder> (Category.class,R.layout.item_menu,MenuViewHolder.class,category) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuname.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void OnClick(View view, int position, boolean isLongClick) {
Toast.makeText(navi.this,""+clickItem.getName(),Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
};
recycle_menu.setAdapter(adapter);
}
This is my MenuviewHolder class:I just created a database for images in firebase and linking it to my app, but its not showing images just background.
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtMenuname;
public ImageView imageView;
private ItemClickListener itemClickListener;
public MenuViewHolder(View itemView) {
super(itemView);
txtMenuname = (TextView)itemView.findViewById(R.id.menu_name);
itemView = (ImageView)itemView.findViewById(R.id.menu_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener){
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.OnClick(view,getAdapterPosition(),false);
}
}
Adapter Code to link the images and name to app using firebaseUI
public class Category {
private String Name;
private String Image;
public Category(){
}
public Category(String name, String image){
Name = name;
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
private void loadMenu() {
FirebaseRecyclerAdapter<Category,MenuViewHolder>
adapter = new
FirebaseRecyclerAdapter <Category, MenuViewHolder>
(Category.class,R.layout.item_menu,
MenuViewHolder.class,category) {
#Override
protected void
populateViewHolder(MenuViewHolder viewHolder,
Category model, int position) {
viewHolder.txtMenuname.setText(model.getName());
If (model.getimage() != null){
Picasso.with(getapplicationcontext()).
load (model.getImage())
.into(viewHolder.imageView);}
else {//Toast here}
final Category clickItem = model;
viewHolder.setItemClickListener(new
ItemClickListener() {
#Override
public void OnClick(View view, int position,
boolean isLongClick) {
Toast.makeText(navi.this,""+clickItem.getName(),
Toast.LEN
GTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
}
};
recycle_menu.setAdapter(adapter);
}