How to get data from firestore when click on recyclerView - android

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);
}
});

Related

How do I add an OnClickListener And An Animation In A RecyclerView?

Okay so I have RecyclerView in which I retrieve some data from Firebase realtime database and I have a SearchView which filters my database. Now I want two things
I want an OnClicListener in my activity with which I could open a fragment by clicking on of the items.
I want to apply animation to my RecyclerView every time I scroll down.
Note: The OnClickListener should also work after filtering the data.
So far I am unable to achieve this. Here is my code
Adapter Class -> AdapterClass.java
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
ArrayList<Deal> list;
public AdapterClass(ArrayList<Deal> list)
{
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_holder,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.id.setText(list.get(i).getDealId());
myViewHolder.desc.setText(list.get(i).getDealDisc());
}
#Override
public int getItemCount() {
return list.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder{
TextView id,desc;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id= itemView.findViewById(R.id.dealId);
desc=itemView.findViewById(R.id.description);
}
}
}
Model Class -> Deal.java
public class Deal {
private String dealDisc;
private String dealId;
private String dealImage;
private String price;
public Deal() {
}
public Deal(String dealDisc, String dealId, String dealImage, String price) {
this.dealDisc = dealDisc;
this.dealId = dealId;
this.dealImage = dealImage;
this.price = price;
}
public String getDealDisc() {
return dealDisc;
}
public void setDealDisc(String dealDisc) {
this.dealDisc = dealDisc;
}
public String getDealId() {
return dealId;
}
public void setDealId(String dealId) {
this.dealId = dealId;
}
public String getDealImage() {
return dealImage;
}
public void setDealImage(String dealImage) {
this.dealImage = dealImage;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
Main Activity -> MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Deal> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ref= FirebaseDatabase.getInstance().getReference().child("rana");
recyclerView = findViewById(R.id.rv);
searchView=findViewById(R.id.searchView);
}
#Override
protected void onStart() {
super.onStart();
if (ref != null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Deal.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
if (searchView != null)
{
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
}
private void search(String str) {
ArrayList<Deal> myList = new ArrayList<>();
for (Deal object : list)
{
if (object.getDealDisc().toLowerCase().contains(str.toLowerCase()) || object.getDealId().toLowerCase().contains(str.toLowerCase()))
{
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
recyclerView.setAdapter(adapterClass);
}
}
myViewHolder.id.setonclickListener()

Pass data recycler adapter to other activity using Firebase

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);
}
});

How to pass document id of Firestore document through OnclickListener?

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.

RecyclerView Android Json

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.

Update value on Recyclerview click listener

i develop app using firebase to upload files and view it in Recyclerview
when i click on any item should take me to another activity and view the file in webView the issue is when i click on any item take the first file uploaded to firebase , i need when i click in any item take the file for this item
public class postShows extends AppCompatActivity {
private RecyclerView postlist;
private DatabaseReference mdatabase;
private FirebaseAuth auth;
ImageView imagepostl;
TextView textname;
String ma,mmmmmm;
PostUtils m;
Context context;
public static String imageURL, fileType,fileNAme;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_shows);
mdatabase = FirebaseDatabase.getInstance().getReference().child(PostNew.item);
auth = FirebaseAuth.getInstance();
imagepostl = (ImageView) findViewById(R.id.imagefilesource);
textname = (TextView) findViewById(R.id.textfilename);
postlist = (RecyclerView) findViewById(R.id.postRecycle);
postlist.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
postlist.setLayoutManager(linearLayoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<PostUtils, PostViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<PostUtils, PostViewHolder>(
PostUtils.class,
R.layout.post_row,
PostViewHolder.class,
mdatabase
)
{
#Override
protected void populateViewHolder(PostViewHolder viewHolder, PostUtils m, int position) {
fileType = m.getfiletype();
fileNAme=m.getFileName();
// viewHolder.setDesc(m.getDescription());
if (m.getfiletype().equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
// imagepostl.setImageResource(R.drawable.word);
viewHolder.setFileName(m.getFileName());
viewHolder.setWord(imagepostl);
mmmmmm= viewHolder.setImageURL(ma,m);
} else if (m.getfiletype().equals("application/pdf")) {
viewHolder.setFileName(m.getFileName());
viewHolder.setPDF(imagepostl);
mmmmmm= viewHolder.setImageURL(ma,m);
} else if (m.getfiletype().contains("image")) {
viewHolder.setimage(imagepostl);
mmmmmm= viewHolder.setImageURL(ma,m);
} else {
viewHolder.setFileName(m.getFileName());
{
viewHolder.setimage(imagepostl);
}
}
}
#Override
public PostViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
PostViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
viewHolder.setOnClickListener(new PostViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(Kasittestbank.getAppContext(), Kasit.class);
intent.putExtra("imageURL",mmmmmm);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Kasittestbank.getAppContext().startActivity(intent);
}
#Override
public void onItemLongClick(View view, int position) {
Toast.makeText(Kasittestbank.getAppContext(), "Item long clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
return viewHolder;
}
};
postlist.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
View mview;
Bitmap bitmap;
FileOpen fileOpen;
public PostViewHolder(View itemView) {
super(itemView);
mview = itemView;
mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mClickListener.onItemClick(v, getAdapterPosition());
}
});
}
private PostViewHolder.ClickListener mClickListener;
//Interface to send callbacks...
public interface ClickListener {
public void onItemClick(View view, int position);
public void onItemLongClick(View view, int position);
}
public void setOnClickListener(PostViewHolder.ClickListener clickListener) {
mClickListener = clickListener;
}
public void setFileName(String name) {
TextView textName = (TextView) mview.findViewById(R.id.textfilename);
textName.setText(name);
}
public void setWord(ImageView imageResourses) {
ImageView imageView = (ImageView) mview.findViewById(R.id.imagefilesource);
imageView.setImageResource(R.drawable.word);
}
public void setPDF(ImageView imageResourses) {
ImageView imageView = (ImageView) mview.findViewById(R.id.imagefilesource);
imageView.setImageResource(R.drawable.pdf);
}
public void setimage(ImageView imageResourses) {
ImageView imageView = (ImageView) mview.findViewById(R.id.imagefilesource);
imageView.setImageResource(R.drawable.image);
}
public String setImageURL(String url, PostUtils maa){
url=maa.getImageUrl();
return url;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logut:
Logut();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
return super.onOptionsItemSelected(item);
}
public void Logut() {
auth.signOut();
finish();
}
}
When you define a recyclerView, one method you should override is onBindViewHolder. Inside of that method is where you define the content of each element of the recyclerView.
So if you want to each row can be clickable, think you need something like this:
#Override
public void onBindViewHolder(PostViewHolder postViewHolder, int i) {
postViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Definde what happend when the item is clicked
//To identify which row, you can use postViewHolder.getAdapterPosition();
}
});
}
Let me know if works.

Categories

Resources