I need to design the bus seat view in android application and I have seat positions in matrix format. For example
a1.row=4;
a1.column=5;
I only need to set those seats in gridview based on their matrix position. Other spaces will be blank or empty in matrix. After showing these seat view if I choose specific seat then that seat related object will be added in a list of object and if I deselect it will be removed from the list of object. Can anyone help me to find out a solution for this ? Is it possible to implement this using gridview but I will set the item in grid view using its matrix position
Try this code
Activityclass
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rv_list);
showSeatList();
}
private void showSeatList()
{
List<SeatModel> seatModels = new ArrayList<>();
seatModels.add(new SeatModel("1","A",false));
seatModels.add(new SeatModel("2","B",false));
seatModels.add(new SeatModel("3","C",false));
seatModels.add(new SeatModel("4","D",false));
seatModels.add(new SeatModel("5","E",false));
seatModels.add(new SeatModel("6","F",false));
seatModels.add(new SeatModel("7","G",false));
seatModels.add(new SeatModel("8","H",false));
seatModels.add(new SeatModel("9","I",false));
seatModels.add(new SeatModel("10","J",false));
SeatSelectionAdapter adapter = new SeatSelectionAdapter(this,seatModels);
recyclerView.setLayoutManager(new GridLayoutManager(this, 5));
recyclerView.setAdapter(adapter);
}
}
Adapter Class
public class SeatSelectionAdapter extends RecyclerView.Adapter<SeatSelectionAdapter.ViewHolder>
{
private List<SeatModel> seatModelList;
private LayoutInflater inflater;
private Context context;
public SeatSelectionAdapter(Context context, List<SeatModel>models)
{
this.seatModelList = models;
inflater = LayoutInflater.from(context);
this.context = context;
}
#NonNull
#Override
public SeatSelectionAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.model_seat,parent,false);
return new SeatSelectionAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SeatSelectionAdapter.ViewHolder holder, int position) {
SeatModel model = seatModelList.get(position);
holder.setData(model);
}
#Override
public int getItemCount() {
return seatModelList.size();
}
class ViewHolder extends RecyclerView.ViewHolder
{
private CardView cardView;
private LinearLayout lnLayout;
private TextView tvSeat;
private ViewHolder(View view) {
super(view);
tvSeat = view.findViewById(R.id.tv_seat);
cardView = view.findViewById(R.id.cv_card);
lnLayout = view.findViewById(R.id.ln_layout);
}
#SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
private void setData(final SeatModel model)
{
tvSeat.setText(model.getSeat());
if(model.isSelect())
lnLayout.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
else lnLayout.setBackgroundColor(context.getResources().getColor(R.color.white));
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(model.isSelect())
{
model.setSelect(false);
Toast.makeText(context,"Seat not selected",Toast.LENGTH_LONG).show();
}
else{
model.setSelect(true);
Toast.makeText(context,"Seat selected",Toast.LENGTH_LONG).show();
}
notifyDataSetChanged();
}
});
}
}
}
Model Class
public class SeatModel
{
private String id,seat;
private boolean isSelect;
public SeatModel(String id, String seat, boolean isSelect) {
this.id = id;
this.seat = seat;
this.isSelect = isSelect;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSeat() {
return seat;
}
public void setSeat(String seat) {
this.seat = seat;
}
}
Related
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);
}
}
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);
}
}
This is my adapter for recycle view
CategoryAdapter Class
public class CategoryRAdapter extends RecyclerView.Adapter<CategoryRAdapter.MyViewHolder> {
private Context mcontext;
private List<Food> mData;
RequestOptions option;
public CategoryRAdapter(Context mcontext, List<Food> mData) {
this.mcontext = mcontext;
this.mData = mData;
option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Food current = mData.get(position);
holder.tv_Name.setText(current.getName());
holder.tv_Rating.setText(current.getRating());
holder.tv_Descip.setText(current.getDescrip());
holder.tv_Category.setText(current.getCateg());
Glide.with(mcontext).load(mData.get(position).getImages()).apply(option).into(holder.img_Thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Name;
TextView tv_Rating;
TextView tv_Descip;
TextView tv_Category;
ImageView img_Thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_Name = itemView.findViewById(R.id.food_name);
tv_Rating = itemView.findViewById(R.id.rating);
tv_Descip = itemView.findViewById(R.id.desc);
tv_Category = itemView.findViewById(R.id.category);
img_Thumbnail = itemView.findViewById(R.id.thumbnail);
}
}
}
This is my model
Food Class
public class Food {
String Name;
String Images;
String Descrip;
String Rating;
String Categ;
public Food() {
}
public Food(String name, String images, String descrip, String rating, String categ) {
this.Name = name;
this.Images = images;
this.Descrip = descrip;
this.Rating = rating;
this.Categ = categ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImages() {
return Images;
}
public void setImages(String images) {
Images = images;
}
public String getDescrip() {
return Descrip;
}
public void setDescrip(String descrip) {
Descrip = descrip;
}
public String getRating() {
return Rating;
}
public void setRating(String rating) {
Rating = rating;
}
public String getCateg() {
return Categ;
}
public void setCateg(String categ) {
Categ = categ;
}
}
My mian activity
CategoryActivity Class
public class CategoriaActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Food> dbObjects;
private RecyclerView.Adapter adapter;
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
TextView l_nombre,l_precio;
Button l_finalizar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria);
recyclerView = findViewById(R.id.recycle_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dbObjects = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objList, ParseException e) {
if (e == null) {
for (ParseObject obj : objList) {
Food food = new Food();
food.setName(obj.getString("Name"));
food.setDescrip(obj.getString("Descrip"));
food.setRating(obj.getString("Rating"));
food.setCateg(obj.getString("Categ"));
food.setImages(obj.getString("Images"));
dbObjects.add(food);
}
} else {
FancyToast.makeText(CategoriaActivity.this, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, true).show();
}
}
});
adapter = new CategoryRAdapter(this, dbObjects);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.shoppingFlot);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
carritopop();
}
});
}
private void carritopop() {
dialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.pop_cart,null);
l_finalizar = view.findViewById(R.id.l_finalizar);
l_finalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pago();
}
});
dialogBuilder.setView(view);
dialog = dialogBuilder.create();
dialog.show();
}
private void pago() {
Intent intent = new Intent(CategoriaActivity.this, PagoActivity.class);
startActivity(intent);
}
}
I dont know whats wrong with the code, the recycle view aint working, it aint showing any items, i would really appreciate if someone could help me out and notice something wrong in my code
Call adapter.notifyDataSetChanged() in your query done callback, this will notify the adapter that the list has changed. This is happening because when you set the adapter, the list was empty as the query was running in background. Once it completes, you have to tell the adapter that new data has been added to list:
if (e == null) {
for (ParseObject obj : objList) {
...
}
adapter.notifyDataSetChanged();
}
Also, create your adapter before you send the query otherwise it may result in NullPointerException in case data is loaded before the next statement executes (highly unlikely but never hurts to be safe).
dbObjects = new ArrayList<>();
adapter = new CategoryRAdapter(this, dbObjects);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
I recommend you to use RxJava2 to user asynchronous methods, it's awesome... And about the problem, maybe your data is not ready when you're already creating the adapter with the ArrayList.
Try to move the recyclerView.setAdapter() to inside the FindCallback after create the Food Objects.
I was just playing around with some code, learning new things, when I ran into this problem... I'm trying to pass a variable from my RecylcerViewAdapter to a method in MainActivity, but I just can't seem to accomplish it.
I tried a lot of different thing with interfaces and casting, but nothing did the trick. Since I'm fairly new to all of this, maybe I'm making a trivial mistake somewhere?
My Interface:
public interface AdapterCallback {
void onMethodCallback(int id);
}
This is my adapter class:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private List<Post> postList;
private Context context;
private AdapterCallback listener;
public PostAdapter() {
}
public PostAdapter(List<Post> postList, Context context) {
this.postList = postList;
this.context = context;
}
public void setListener(AdapterCallback listener) {
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.tvTitle.setText(postList.get(position).getTitle());
viewHolder.tvBody.setText(new StringBuilder(postList.get(position).getBody().substring(0, 20)).append("..."));
viewHolder.tvId.setText(String.valueOf(postList.get(position).getUserId()));
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = postList.get(position).getId();
if (listener != null) {
listener.onMethodCallback(id);
}
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvBody;
TextView tvId;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvBody = itemView.findViewById(R.id.tvBody);
tvId = itemView.findViewById(R.id.tvId);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
And my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivityLog";
private CompositeDisposable disposable = new CompositeDisposable();
#BindView(R.id.rvPosts)
RecyclerView rvPosts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
rvPosts.setHasFixedSize(true);
rvPosts.setLayoutManager(new LinearLayoutManager(this));
populateList();
logItems();
}
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
}
});
}
public void logItems() {
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
The populateList() method works just fine, but the logItems() method is the problem.
So when i click on a view in RecyclerView I expect the log to output the title, description and ID of the post that was clicked. nut nothing happens...
So, any help would be appreciated.
Make adapter global variable i.e. a field. Use the same object to set every properties.
private PostAdapter adapter;
Replace your logItems method with this:
public void logItems() {
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
And populateList with this:
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
logItems();
}
});
}
And don't call logItems() from onCreate
This is how I implement with my ListAdapters:
public class FeedbackListAdapter extends RecyclerView.Adapter<FeedbackListAdapter.ViewHolder> {
private final ArrayList<Feedback> feedbacks;
private View.OnClickListener onItemClickListener;
private View.OnLongClickListener onItemLongClickListener;
private final Context context;
public FeedbackListAdapter(ArrayList<Feedback> feedbacks, Context context) {
this.feedbacks = feedbacks;
this.context = context;
}
public void setItemClickListener(View.OnClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(View.OnLongClickListener onItemLongClickListener){
this.onItemLongClickListener = onItemLongClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder{
final TextView feedback, created, updated;
final LinearLayout mainLayout;
ViewHolder(View iv) {
super(iv);
/*
* Associate layout elements to Java declarations
* */
mainLayout = iv.findViewById(R.id.main_layout);
feedback = iv.findViewById(R.id.feedback);
created = iv.findViewById(R.id.created_string);
updated = iv.findViewById(R.id.updated_string);
}
}
#Override
public int getItemCount() {
return feedbacks.size();
}
#Override
#NonNull
public FeedbackListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_feedback_table_row, parent, false);
return new FeedbackListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final #NonNull FeedbackListAdapter.ViewHolder holder, final int position) {
/*
* Bind data to layout
* */
try{
Feedback feedback = feedbacks.get(position);
holder.feedback.setText(feedback.getContent());
holder.created.setText(feedback.getCreated());
holder.updated.setText(feedback.getUpdated());
holder.mainLayout.setOnClickListener(this.onItemClickListener);
holder.mainLayout.setOnLongClickListener(this.onItemLongClickListener);
holder.mainLayout.setTag(feedback.getDbID());
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
holder.mainLayout.setBackgroundResource(outValue.resourceId);
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
In onPopulateList you create an adaptor:
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
However in public void logItems() { you used a different adapter
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
Therefore the list is being populated with 1 adapter, but you are setting the listener on an unused second adapter.
The fix is to use the same adapter for both. If you make the adapater a field, and don't create a new one inside of logItems, but just set your listener it should work.
i.e.
// as a field in your class
private PostAdapter adapter;
then
// in `populateList()`
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
and
// in `logItems()`
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
In Adapter
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListAdapter.OrderItemViewHolder> {
private Context mCtx;
ProgressDialog progressDialog;
//we are storing all the products in a list
private List<CustomerModel> customeritemList;
public CustomerListAdapter(Context mCtx, List<CustomerModel> orderitemList) {
this.mCtx = mCtx;
this.customeritemList = orderitemList;
progressDialog = new ProgressDialog(mCtx);
}
#NonNull
#Override
public OrderItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.activity_customer_list, null);
return new OrderItemViewHolder(view, mCtx, customeritemList);
}
#Override
public void onBindViewHolder(#NonNull OrderItemViewHolder holder, int position) {
CustomerModel customer = customeritemList.get(position);
try {
//holder.textViewPINo.setText("PINo \n"+Integer.toString( order.getPINo()));
holder.c_name.setText(customer.getCustomerName());
holder.c_address.setText(customer.getAddress());
holder.c_contact.setText(customer.getMobile());
holder.i_name.setText(customer.getInteriorName());
holder.i_contact.setText(customer.getInteriorMobile());
holder.i_address.setText(customer.getAddress());
} catch (Exception E) {
E.printStackTrace();
}
}
#Override
public int getItemCount() {
return customeritemList.size();
}
class OrderItemViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
AlertDialog.Builder alert;
private Context mCtx;
TextView c_name, c_contact, c_address, i_name, i_contact, i_address;
TextView OrderItemID, MaterialType, Price2, Qty, AQty;
//we are storing all the products in a list
private List<CustomerModel> orderitemList;
public OrderItemViewHolder(View itemView, Context mCtx, List<CustomerModel> orderitemList) {
super(itemView);
this.mCtx = mCtx;
this.orderitemList = orderitemList;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
// CatelogOrderDetailModel catelogOrderDetailModel = new CatelogOrderDetailModel();
c_name = itemView.findViewById(R.id.customerName);
c_contact = itemView.findViewById(R.id.contact);
c_address = itemView.findViewById(R.id.address);
i_name = itemView.findViewById(R.id.interiorName);
i_address = itemView.findViewById(R.id.interiorAddress);
i_contact = itemView.findViewById(R.id.interiorContact);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
}
#Override
public boolean onLongClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
if (v.getId() == itemView.getId()) {
// showUpdateDeleteDialog(order);
try {
} catch (Exception E) {
E.printStackTrace();
}
Toast.makeText(mCtx, "lc: ", Toast.LENGTH_SHORT).show();
}
return true;
}
}
}
I'm trying to list data from serializable object but it doesn't work show nothing.
I am listing information from a recyclerview with serialized object. When passing to another activity, the recyclerview does not show any data.
Sorry about my english.
MainActivity
private void onOrderProduct() {
bOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cart cart = new Cart();
cart.setComida(tvTitle.getText().toString());
cart.setPreco(tvTotal.getText().toString());
cart.setQuantidade(tvQtd.getText().toString());
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("cart", cart);
startActivity(intent);
}
});
}
SecondActivity
public class SecondActivity extends AppCompatActivity {
RecyclerView rvCart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
rvCart = (RecyclerView) findViewById(R.id.tela5recycler_view);
rvCart.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(this);
rvCart.setLayoutManager(manager);
if (getIntent().getSerializableExtra("cart") != null) {
Intent intent = getIntent();
Cart cart = (Cart) intent.getSerializableExtra("cart");
ArrayList<Cart> eList = new ArrayList<>() cart;
Adapter adapter =new Adapter(getApplicationContext(), eList );
rvCart.setAdapter(adapter);
}
}
}
Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.ItemViewHolder> {
private Context context;
private ArrayList<Cart> itemList;
public Adapter(Context context, ArrayList<Cart> itemList){
this.context = context;
this.itemList = itemList;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.from(parent.getContext())
.inflate(R.layout.adapter_card, parent, false);
ItemViewHolder itemViewHolder = new ItemViewHolder(view);
return itemViewHolder;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
Cart item = itemList.get(position);
holder.tvQtdcard.setText(item.getQuantidade());
holder.tvComidacard.setText(item.getComida());
holder.tvPrecocard.setText(item.getPreco());
}
#Override
public int getItemCount() {
if(itemList != null){
return itemList.size();
}
return 0;
}
public static class ItemViewHolder extends RecyclerView.ViewHolder{
public CardView cvItem;
public TextView tvQtdcard, tvComidacard, tvPrecocard;
public ItemViewHolder(View itemView) {
super(itemView);
cvItem = (CardView)itemView.findViewById(R.id.tela1_1_1_1_1card);
tvQtdcard = (TextView)itemView.findViewById(R.id.tela5qtdcard);
tvComidacard = (TextView)itemView.findViewById(R.id.tela5comidacard);
tvPrecocard = (TextView)itemView.findViewById(R.id.tela5precocard);
}
}
}
Cart.class Serializable
import java.io.Serializable;
public class Cart implements Serializable{
private static final long serialVersionUID = 42L;
private String comida;
private String quantidade;
private String preco;
public String getComida() {
return comida;
}
public void setComida(String comida) {
this.comida = comida;
}
public String getQuantidade() {
return quantidade;
}
public void setQuantidade(String quantidade) {
this.quantidade = quantidade;
}
public String getPreco() {
return preco;
}
public void setPreco(String preco) {
this.preco = preco;
}
public String toString(){
return comida;
}
}
You are missing adapter.notifyDataSetChanged() after and you are passing empty arraylist eList
ArrayList<Cart> eList = new ArrayList<>();
eList.add(cart);
Adapter adapter =new Adapter(getApplicationContext(), eList );
rvCart.setAdapter(adapter);
To pass the serialized object
Solution 1 (Hackytack solution)
public class CardListHolder implements Serializable{
private ListcardList=new ArrayList<>();
public List<Card>getCardList(){
return cardList;
}
public void setCardList(List<Card> cardList){
this.cardList=cardList;
}
}
Use this holder object to pass the list of card
Solution 2
Implement Parcelable for Card object, it can pass list of card but it is little bit complex to understand. Try www.parcelabler.com to auto generate the Parceable class for Card.