How do i set data in RecylerView using Retrofit.I have tried but i was not able to performed it successfully.
Here is my code:
JSON DATA is :
{
"model": [
{
"id": "1",
"brand_name": "Audi",
"brand_logo": "1495456122.",
},
{
"id": "3",
"brand_name": "BMW",
"brand_logo": "1495451144.",
}
]
}
BrandSelectActivity.java
public class BrandSelectActivity extends AppCompatActivity implements View.OnClickListener {
ProgressDialog pDialog;
Button btn_addVehicle;
BrandListRecyclerAdapter adapter;
RecyclerView recyclerView_brand;
public ImageView carBrandImg;
public TextView carBrandName;
private static String TAG = BrandSelectActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand_select);
carBrandImg = (ImageView)findViewById(R.id.carBrandImg);
carBrandName = (TextView)findViewById(R.id.carBrandName);
recyclerView_brand = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setCancelable(true);
pDialog.setMessage("Please Wait...");
pDialog.show();
ArrayList<BrandModel> brandModelArrayList = new ArrayList<BrandModel>();
BrandListRecyclerAdapter brandAdapter = new BrandListRecyclerAdapter(BrandSelectActivity.this, brandModelArrayList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView_brand.setLayoutManager(mLayoutManager);
recyclerView_brand.setAdapter(brandAdapter);
brandAdapter.setItemClickListener(new BrandListRecyclerAdapter.MyClickListerer() {
#Override
public void onItemClick(int position, View view) {
Intent sosIntent = new Intent(BrandSelectActivity.this, ModelSelectActivity.class);
startActivity(sosIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
callBrandSelect();
}
private void callBrandSelect() {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<BrandSelectResponse> call = apiService.saveBrand("1");
call.enqueue(new Callback<BrandSelectResponse>() {
#Override
public void onResponse(Call<BrandSelectResponse> call, retrofit2.Response<BrandSelectResponse> response) {
BrandSelectResponse br= response.body();
List<BrandSelectResponse.ModelBean> modelList = br.getModel();
modelList.size();
modelList.get(0).getBrand_logo();
modelList.get(0).getBrand_name();
pb.dismiss();
}
#Override
public void onFailure(Call<BrandSelectResponse>call, Throwable t) {
Toast.makeText(BrandSelectActivity.this,"Opps ..!!Failed to
connect to our server.. Try Again later..",Toast.LENGTH_SHORT).show();
Log.e(TAG, t.toString());
}
});
}
#Override
public void onClick(View v) {
}
}
BrandListRecyclerAdapter.java
public class BrandListRecyclerAdapter extends RecyclerView.Adapter<BrandListRecyclerAdapter.MyViewHolder> {
Context mcontext;
List<BrandSelectResponse> brandModelArrayList;
public LayoutInflater inflater;
public static MyClickListerer myClickListerer;
public BrandListRecyclerAdapter(Context context, ArrayList<BrandSelectResponse> brandModelArrayList) {
this.mcontext = context;
this.brandModelArrayList=brandModelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_brand, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
BrandSelectResponse current = brandModelArrayList.get(position);
holder.setData((BrandSelectResponse) brandModelArrayList,position);
holder.carBrandName.setText(current.getBrand_name());
holder.carBrandImg.setImageResource(current.getBrand_logo());
}
public interface MyClickListerer {
void onItemClick(int position, View view);
}
public void setItemClickListener(MyClickListerer myClickListerer) {
this.myClickListerer = myClickListerer;
}
#Override
public int getItemCount() {
return brandModelArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView carBrandImg;
public TextView carBrandName;
BrandSelectResponse brandModelArrayList;
LinearLayout current;
int position;
public MyViewHolder(View itemView) {
super(itemView);
carBrandImg = (ImageView) itemView.findViewById(R.id.carBrandImg);
carBrandName = (TextView) itemView.findViewById(R.id.carBrandName);
}
public void setData(BrandSelectResponse current, int position) {
carBrandName.setText(brandModelArrayList.getBrand_name());
carBrandImg.setImageResource(brandModelArrayList.getBrand_logo());
this.position = position;
this.brandModelArrayList = current;
}
#Override
public void onClick(View v) {
myClickListerer.onItemClick(getAdapterPosition(), v);
}
}
}
BrandSelectResponse.java
public class BrandSelectResponse implements Serializable{
private List<ModelBean> model;
public BrandSelectResponse(List<ModelBean> model) {
this.model = model;
}
public List<ModelBean> getModel() {
return model;
}
public void setModel(List<ModelBean> model) {
this.model = model;
}
public static class ModelBean {
private String id;
private String brand_name;
private String brand_logo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_logo() {
return brand_logo;
}
public void setBrand_logo(String brand_logo) {
this.brand_logo = brand_logo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
You give to adapter EMPTY list.
You never add data to brandModelArrayList.
Next time try to look at the logcat, what is the exception and which line is the problem.
Related
Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}
I'm developing an android app for online order. User needs to click on an food item in recyclerView and I'm trying to send the food ID to the AddOrderActivity. How can I get the FId and pass it to the new activity?
CustomerHomeFragment.java
public class CustomerHomeFragment extends Fragment {
private RecyclerView recyclerView;
private FoodsAdapter adapter;
private List<Food> foodList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home_customer, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
Call<FoodsResponse> call = RetrofitClient.getInstance().getApi().getFoods();
call.enqueue(new Callback<FoodsResponse>() {
#Override
public void onResponse(Call<FoodsResponse> call, Response<FoodsResponse> response) {
foodList = response.body().getFoods();
adapter = new FoodsAdapter(getActivity(), foodList);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<FoodsResponse> call, Throwable t) {
}
});
}
}
public class FoodsAdapter extends RecyclerView.Adapter implements View.OnClickListener{
private Context mCtx;
private List<Food> foodList;
public FoodsAdapter(Context mCtx, List<Food> foodList) {
this.mCtx = mCtx;
this.foodList = foodList;
}
#NonNull
#Override
public FoodsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_foods, parent, false);
return new FoodsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FoodsViewHolder holder, int position) {
Food food = foodList.get(position);
holder.textViewFName.setText(food.getFName());
holder.textViewUnitPrice.setText(String.format("%d", food.getUnitPrice()));
holder.textViewAvailCount.setText(String.format("%d", food.getAvailCount()));
}
#Override
public int getItemCount() {
return foodList.size();
}
//////////////
#Override
public void onClick(View view) {
Intent intent = new Intent(this.mCtx, AddOrderActivity.class);
this.mCtx.startActivity(intent);
}
/////////////////
class FoodsViewHolder extends RecyclerView.ViewHolder {
TextView textViewFName, textViewUnitPrice, textViewAvailCount;
public FoodsViewHolder(View itemView) {
super(itemView);
textViewFName = itemView.findViewById(R.id.textViewFName);
textViewUnitPrice = itemView.findViewById(R.id.textViewUnitPrice);
textViewAvailCount = itemView.findViewById(R.id.textViewAvailCount);
}
}
}
public class Food {
private int fid, unitprice, availcount;
private String fname;
public Food(int fid, String fname, int unitprice, int availcount) {
this.fid = fid;
this.fname = fname;
this.unitprice = unitprice;
this.availcount = availcount;
}
public int getFId() {
return fid;
}
public String getFName() {
return fname;
}
public int getUnitPrice() {
return unitprice;
}
public int getAvailCount() {
return availcount;
}
}
in the your adapter class inside the onBindViewHolder function add this code
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,NoteActivity.class);
intent.putExtra("note_id", currentNote.getNoteId());
intent.putExtra("note_name",currentNote.getNoteName());
intent.putExtra("note_teacher",currentNote.getNoteTeacher());
intent.putExtra("note_university",currentNote.getNoteUniversity());
intent.putExtra("note_image",currentNote.getNoteImage());
intent.putExtra("note_is_downloaded", currentNote.getIsDownloaded());
intent.putExtra("note_storage_path", currentNote.getStoragePath());
intent.putExtra("note_download_link", currentNote.getNoteDownloadLink());
context.startActivity(intent);
}
});
Image :
I am using Firebase for video status android application, and using recycler view but Firebase daat will not pass first activity to another (second) activity, how I can solve this problem (error)
error Model.videolink' on a null object reference.
App Adepter
public class App_Adepter extends RecyclerView.Adapter<App_Adepter.ViewHolder> {
Model model;
private Context context;
private ArrayList<Model> uploads;
private ProgressDialog pDialog;
private MediaController mediaController;
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public VideoView videoView;
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.rImageView);
videoView = (VideoView) itemView.findViewById(R.id.test_video);
textView = (TextView) itemView.findViewById(R.id.text11);
}
}
public App_Adepter(Context context, ArrayList<Model> uploads) {
this.uploads = uploads;
this.context = context;
}
#Override
public App_Adepter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row, parent, false);
return new App_Adepter.ViewHolder(v);
}
#Override
public void onBindViewHolder(final App_Adepter.ViewHolder holder, final int position) {
final Model upload = uploads.get(position);
/*Video Click*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Full_video.class);
intent.putExtra("posss", model.image);
intent.putParcelableArrayListExtra("Category", uploads);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
final MediaController mediaController = new MediaController(context);
String uriPath = upload.getImage(); //update package name
Uri uri = Uri.parse(uriPath);
holder.textView.setText(upload.getVideolink());
Glide.with(context).load(upload.getImage()).into(holder.imageView);
holder.videoView.setVideoURI(uri);
holder.videoView.start();
holder.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return true;
}
});
holder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
/**** Media control coding ****///
holder.videoView.setMediaController(mediaController);
mediaController.setAnchorView(holder.videoView);
mp.setVolume(0, 0);
}
});
}
});
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return uploads.size();
}
}
Model Class
String image;
String videolink;
public Model() {
}
public static Creator<Model> getCREATOR() {
return CREATOR;
}
public Model(String image,String videolink) {
this.videolink = videolink;
this.image = image;
}
protected Model(Parcel in) {
image = in.readString();
videolink = in.readString();
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public Model createFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
public String getVideolink() {
return videolink;
}
public void setVideolink(String videolink) {
this.videolink = videolink;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(image);
dest.writeString(videolink);
}
Other (Second) Activity
Bundle extra = getIntent().getExtras();
String value = extra.getString("posss");
videoView.setVideoURI(Uri.parse(value));
First Activity
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
progressDialog.dismiss();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Model upload = postSnapshot.getValue(Model.class);
app_models.add(upload);
}
adapter = new App_Adepter(App_screen.this, app_models);
recyclerView.setAdapter(adapter);
if (app_models.size() <= 0) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.GONE);
}
}
Try this code..
make interface into adapter class for click handel..
onItemClick onItemClick;
public void setOnItemClick(adapterDemo.onItemClick onItemClick) {
this.onItemClick = onItemClick;
}
interface onItemClick{
void onClickData(Model data);
}
then onBindView method changes..
#Override
public void onBindViewHolder(#NonNull adapterDemo.ViewHolder viewHolder, int i) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onClickData(upload);
}
});
}
after that in activity define adapter and bind into recyclerview.. make sure your adapter object not null..
adapterDemo.setOnItemClick(new adapterDemo.onItemClick() {
#Override
public void onClickData(Model data) {
// here get click object data..
Intent intent = new Intent(context, Full_video.class);
intent.putExtra("posss", model.image);
intent.putParcelableArrayListExtra("Category", uploads);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
I have already retrieved data from firestore to RecyclerView, then I need to click my recyclerView and show the data that i click to new Activity. How to get the data?
This is the code for Main Activity
List<FoodModel>models;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_home);
db = FirebaseFirestore.getInstance();
getData();
}
public void getData(){
models = new ArrayList<>();
db.collection("Food").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()){
for (DocumentSnapshot docSnap: documentSnapshots.getDocuments()) {
FoodModel model = docSnap.toObject(FoodModel.class);
models.add(model);
foodAdapter = new FoodAdapter(models, getApplicationContext(), new FoodAdapter.OnFoodClick() {
#Override
public void OnClick(FoodModel food) {
Intent intent = new Intent(MainActivity.this, FoodActivity.class);
startActivity(intent);
}
});
recyclerView.setAdapter(foodAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
This is the Adapter
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder>{
LayoutInflater inflater;
List<FoodModel> foodModels;
OnFoodClick listener;
Context context;
public FoodAdapter(List<FoodModel> foodModels, Context context, OnFoodClick listener) {
this.foodModels = foodModels;
this.context = context;
this.listener = listener;
inflater = LayoutInflater.from(context);
}
#Override
public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.view_holder_food, null, false);
FoodViewHolder holder = new FoodViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(FoodViewHolder holder, int position) {
FoodModel model = foodModels.get(position);
holder.tvName.setText(model.getName());
}
#Override
public int getItemCount() {
return foodModels.size();
}
public void addItem(FoodModel food){
foodModels.add(food);
notifyDataSetChanged();
}
public class FoodViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
public FoodViewHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition();
listener.OnClick(foodModels.get(position));
}
});
}
}
public interface OnFoodClick{
public void OnClick(FoodModel food);
}
}
This is my second Activity. i want to show name, type and price from Firestore. when i click the recycler view, the data not show in the activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
firedb = FirebaseFirestore.getInstance();
tvName = findViewById(R.id.tv_food_name);
tvType = findViewById(R.id.tv_type);
tvPrice = findViewById(R.id.tv_price);
getFoodData();
}
private void getFoodData(){
firedb.collection("Food").document().get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()){
loadData(documentSnapshot.toObject(FoodModel.class));
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
private void loadData(FoodModel foodModel){
tvName.setText(foodModel.getFoodName());
tvType.setText(foodModel.getType());
tvPrice.setText(foodModel.getPrice());
}
}
This is the foodModel
public class FoodModel {
String foodName;
String type;
String price;
public FoodModel() {
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
make an interface to handle recycler view click event like this ..
define below code into adapter.
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
String data=mStringList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
then after in activity adapter bind into recycler view then call this method to get your click item on recycler view ..
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
Log.d("Click Value",str);
}
});
I want to add onClickListener to items in the recyclerview showing data from firestore. OnClick should pass the corresponding document id through intent . Pleas help
ProductFragment showing the data
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private FirebaseFirestore firestoreDB;
private RecyclerView productRecyclerView;
public ProductFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
firestoreDB = FirebaseFirestore.getInstance();
productRecyclerView = (RecyclerView) view.findViewById(R.id.Product_RecyclerView);
LinearLayoutManager recyclerLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
productRecyclerView.setLayoutManager(recyclerLayoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(productRecyclerView.getContext(),
recyclerLayoutManager.getOrientation());
productRecyclerView.addItemDecoration(dividerItemDecoration);
getDocumentsFromCollection();
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void getDocumentsFromCollection() {
firestoreDB.collection("products").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
//List<Event> eventList = new ArrayList<>();
List<DocumentSnapshot> documents = task.getResult().getDocuments();
ProductAdapter recyclerViewAdapter = new ProductAdapter(documents, getActivity(), firestoreDB);
recyclerViewAdapter.setOnItemClickListener(new ProductAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
// Go to the details page for the selected product
}
});
productRecyclerView.setAdapter(recyclerViewAdapter);
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
firestoreDB.collection("products")
.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
}
});
}
}
Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
public static ClickListener clickListener;
public List<DocumentSnapshot> documents;
private Context context;
private FirebaseFirestore firestoreDB;
public ProductAdapter(List<DocumentSnapshot> list, Context ctx, FirebaseFirestore firestore) {
documents = list;
context = ctx;
firestoreDB = firestore;
}
#Override
public int getItemCount() {
return documents.size();
}
#Override
public ProductAdapter.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
ProductAdapter.ViewHolder viewHolder =
new ProductAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ProductAdapter.ViewHolder holder, int position) {
final int itemPos = position;
final DocumentSnapshot snapshot = documents.get(position);
holder.item_name.setText(snapshot.getString("Product"));
holder.price.setText("Rs " + snapshot.getString("Cost") + "/" + snapshot.getString("Per"));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView item_name;
public TextView price;
public ViewHolder(View view) {
super(view);
itemView.setOnClickListener(this);
item_name = view.findViewById(R.id.List_maintext);
price = view.findViewById(R.id.List_subtext);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
ProductAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
I tried some methods but all of them crashed.
I need to show a detailed view of the item clicked
You can something like this: Create POJO class and get data from this class.
POJO.class
public class Info {
String product;
String cost;
String per;
#Exclude
private String key;
public Info(){
}
public Info(String product, String cost, String per){
this.product = product;
this.cost = cost;
this.per = per;
}
public <T extends Info> T withId(#NonNull final String id) {
this.key = id;
return (T) this;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getPer() {
return per;
}
public void setPer(String per) {
this.per = per;
}
}
Your fragment, your method
List<Info> documents = new ArrayList<>(); //before onCreate method
public void getDocumentsFromCollection() {
firestoreDB.collection("products").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot snap : task.getResult()){
Info model =snap.toObject(Info.class).withID(snap.getID());
documents.add(model);
ProductAdapter recyclerViewAdapter = new ProductAdapter(documents, getActivity(), firestoreDB);
recyclerViewAdapter.setOnItemClickListener(new ProductAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
// Go to the details page for the selected product
}
});
productRecyclerView.setAdapter(recyclerViewAdapter);
productRecyclerView.notifyDataSetChanged();
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
firestoreDB.collection("products")
.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
}
});
}
Adapter your:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
public static ClickListener clickListener;
public List<Info> documents;
private Activity context;
private FirebaseFirestore firestoreDB;
public ProductAdapter(List<Info> list, Activitx ctx, FirebaseFirestore firestore) {
documents = list;
context = ctx;
firestoreDB = firestore;
}
#Override
public int getItemCount() {
return documents.size();
}
#Override
public ProductAdapter.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
ProductAdapter.ViewHolder viewHolder =
new ProductAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ProductAdapter.ViewHolder holder, int position) {
final int itemPos = position;
final Info model = documents.get(position);
holder.item_name.setText(model.getProduct());
holder.price.setText("Rs " + model.getCost() + "/" + model.getPer());
holder.itemView.setOnClicListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openNewActivity = new Intent(context, YourNewActivity.class);
openNewActivity.putExtra("id", model.getId());
openNewActivity.putExtra("product", model.getProduct());
context.startActivity(openNewActivity);
}
});
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView item_name;
public TextView price;
public ViewHolder(View view) {
super(view);
itemView.setOnClickListener(this);
item_name = view.findViewById(R.id.List_maintext);
price = view.findViewById(R.id.List_subtext);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
ProductAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
You can try something like this, I think this can help you to solve your problem.
P.S. Sorry for my english.