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.
Related
I made an app that fetches and stores data from the Android application to the Firebase, and I made activity that includes RecyclerView in which the data is displayed, but the problem is that when I click on any record in RecyclerView, I want to open another screen that contains the same data that was pressed, and I Try the code mentioned below, but when you press on RecyclerView, the application stops (and I think the problem is in the process of transferring data when I click on the record)
Please help me to solve the problem
The class code
public class EMP_INFO implements Serializable {
private String Id;
private String Name;
private String City;
public EMP_INFO() {
}
public String getEmployeeID() {
return Id;
}
public void setEmployeeID(String ID) {
this.Id = ID;
}
public String getEmployeeName() {
return Name;
}
public void setEmployeeName(String Name) {
this.Name = Name;
}
public String getEmployeeCity() {
return City;
}
public void setEmployeeCity(String City) {
this.City = City;
}
}
The adapter code
public class EMP_INFO_Adapter extends FirebaseRecyclerAdapter<EMP_INFO, EMP_INFO_Adapter.personsViewholder> {
public EMP_INFO_Adapter(#NonNull FirebaseRecyclerOptions<EMP_INFO> options)
{
super(options);
}
#Override
protected void
onBindViewHolder(#NonNull personsViewholder holder, int position, #NonNull EMP_INFO model)
{
holder.F_ID.setText(model.getEmployeeID());
holder.F_name.setText(model.getEmployeeName());
holder.F_city.setText(model.getEmployeeCity());
Intent intent = new Intent(context, FireBase_Save_data_1.class);
intent.putExtra("FB_id1", String.valueOf(model.getEmployeeID()));
intent.putExtra("FB_name1", String.valueOf(model.getEmployeeName()));
intent.putExtra("FB_city1", String.valueOf(model.getEmployeeCity()));
activity.startActivityForResult(intent, 1);
}
#NonNull
#Override
public personsViewholder
onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fire_base_my_row, parent, false);
return new EMP_INFO_Adapter.personsViewholder(view);
}
class personsViewholder extends RecyclerView.ViewHolder { TextView F_ID, F_name, F_city;
public personsViewholder(#NonNull View itemView)
{
super(itemView);
F_ID = itemView.findViewById(R.id.F_ID);
F_name = itemView.findViewById(R.id.F_name);
F_city = itemView.findViewById(R.id.F_city);
}
}
}
The RecyclerView activity code
public class FireBase_Recyclerview_2 extends AppCompatActivity {
private RecyclerView recyclerView;
Button add_button;
EMP_INFO_Adapter adapter;
//EMP_INFO_Adapter_3 adapter;
DatabaseReference mbase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fire_base_recyclerview_2);
add_button = findViewById(R.id.add_button);
recyclerView = findViewById(R.id.recycler1);
// To display the Recycler view linearly
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mbase = FirebaseDatabase.getInstance().getReference("EmployeeInfo") ;
FirebaseRecyclerOptions<EMP_INFO> options = new FirebaseRecyclerOptions.Builder<EMP_INFO>()
.setQuery(mbase, EMP_INFO.class).build();
adapter = new EMP_INFO_Adapter(options);
//adapter = new EMP_INFO_Adapter_3(options);
recyclerView.setAdapter(adapter);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FireBase_Recyclerview_2.this, FireBase_Save_data_1.class);
startActivity(intent);
}
});
}
#Override protected void onStart()
{
super.onStart();
adapter.startListening();
}
#Override protected void onStop()
{
super.onStop();
adapter.stopListening();
}
}
You may put a click Listener on the item inside your adapter's onBindViewHolder,as shown below.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, FireBase_Save_data_1.class);
intent.putExtra("empId", model.getEmployeeID());
intent.putExtra("empName", model.getEmployeeName());
intent.putExtra("empCity", model.getEmployeeCity());
context.startActivity(intent);
}
});
You can't start activity within onBinViewHolder.move that code to viewholder class.
public class EMP_INFO_Adapter extends FirebaseRecyclerAdapter<EMP_INFO, EMP_INFO_Adapter.personsViewholder> {
public EMP_INFO_Adapter(#NonNull FirebaseRecyclerOptions<EMP_INFO> options)
{
super(options);
}
#Override
protected void
onBindViewHolder(#NonNull personsViewholder holder, int position, #NonNull EMP_INFO model)
{
holder.F_ID.setText(model.getEmployeeID());
holder.F_name.setText(model.getEmployeeName());
holder.F_city.setText(model.getEmployeeCity());
}
#NonNull
#Override
public personsViewholder
onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fire_base_my_row, parent, false);
return new EMP_INFO_Adapter.personsViewholder(view);
}
class personsViewholder extends RecyclerView.ViewHolder implements View.OnClickListener
TextView F_ID, F_name, F_city;
public personsViewholder(#NonNull View itemView)
{
super(itemView);
F_ID = itemView.findViewById(R.id.F_ID);
F_name = itemView.findViewById(R.id.F_name);
F_city = itemView.findViewById(R.id.F_city);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id=getAdapterPosition();
Intent intent = new Intent(context, FireBase_Save_data_1.class);
intent.putExtra("FB_id1", String.valueOf(model.get(id).getEmployeeID()));
intent.putExtra("FB_name1", String.valueOf(model.get(id).getEmployeeName()));
intent.putExtra("FB_city1", String.valueOf(model.get(id).getEmployeeCity()));
activity.startActivityForResult(intent, 1);
}
}
}
}
}
I've been trying to get Onclik events on RecyclerView to display the same data that the RecyclerView had in a new activity with even more data that wasn't previously there. Right now I have data like name, phone number but I would like to add morelike website... So far the code I tried is crashing when i click on the View. I don't know what is wrong. can anyone help ?
Here's my main fragment
public class Entreprisesfrag extends android.support.v4.app.Fragment {
RecyclerView recyclerView;
DatabaseReference dbref;
FirebaseDatabase firebaseDatabase;
LinearLayout linearLayout;
LinearLayoutManager linearLayoutManager;
public Entreprisesfrag() {
// Required empty public constructor
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_entreprises, container,
false);
recyclerView= view.findViewById(R.id.recv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager (new LinearLayoutManager(getContext()));
linearLayout= view.findViewById(R.id.entreprise_list_layout);
firebaseDatabase= FirebaseDatabase.getInstance();
dbref= firebaseDatabase.getReference("Entreprises");
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,dbref.orderByChild("nom")) {
#Override
protected void populateViewHolder(ViewHolder viewHolder,
entreprises_class model, int position) {
viewHolder.details(getActivity(), model.getNom(),model.getNum(),
model.getSecteur(), model.getSpécialité(), model.getVille(),
model.getImage());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewHolder viewHolder = super.onCreateViewHolder(parent,
viewType);
viewHolder.setOnClickListener(new ViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView textView=
view.findViewById(R.id.entreprise_nom);
TextView textView1=
view.findViewById(R.id.entreprise_secteur);
TextView textView2=
view.findViewById(R.id.entreprise_sous_secteur);
TextView textView3=
view.findViewById(R.id.entreprise_ville);
TextView textView4=
view.findViewById(R.id.entreprise_num);
ImageView
imageView=view.findViewById(R.id.entreprise_image);
String snom= textView.getText().toString();
String ssec= textView1.getText().toString();
String ssp= textView2.getText().toString();
String sv= textView3.getText().toString();
String snum= textView4.getText().toString();
Drawable drawable= imageView.getDrawable();
Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
Intent i= new Intent(view.getContext(),
entProfileFull.class);
ByteArrayOutputStream byteArrayOutputStream= new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100,
byteArrayOutputStream);
byte[] bytes= byteArrayOutputStream.toByteArray();
i.putExtra("image", bytes);
i.putExtra("nom", snom);
i.putExtra("secteur", ssec);
i.putExtra("spécialité", ssp);
i.putExtra("ville", sv);
i.putExtra("num", snum);
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
return viewHolder;
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public void recherche(String texte){
Query mQuery= dbref.orderByChild("spécialité");
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,mQuery) {
#Override
protected void populateViewHolder(ViewHolder viewHolder,
entreprises_class model, int position) {
viewHolder.details(getActivity(), model.getNom(),model.getNum(),
model.getSecteur(), model.getSpécialité(), model.getVille(),
model.getImage());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewHolder viewHolder = super.onCreateViewHolder(parent,
viewType);
viewHolder.setOnClickListener(new ViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView textView=
view.findViewById(R.id.entreprise_nom);
TextView textView1=
view.findViewById(R.id.entreprise_secteur);
TextView textView2=
view.findViewById(R.id.entreprise_sous_secteur);
TextView textView3=
view.findViewById(R.id.entreprise_ville);
TextView textView4=
view.findViewById(R.id.entreprise_num);
ImageView
imageView=view.findViewById(R.id.entreprise_image);
String snom= textView.getText().toString();
String ssec= textView1.getText().toString();
String ssp= textView2.getText().toString();
String sv= textView3.getText().toString();
String snum= textView4.getText().toString();
Drawable drawable= imageView.getDrawable();
Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
Intent i= new Intent(view.getContext(),
entProfileFull.class);
ByteArrayOutputStream byteArrayOutputStream= new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100,
byteArrayOutputStream);
byte[] bytes= byteArrayOutputStream.toByteArray();
i.putExtra("image", bytes);
i.putExtra("nom", snom);
i.putExtra("secteur", ssec);
i.putExtra("spécialité", ssp);
i.putExtra("ville", sv);
i.putExtra("num", snum);
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
return viewHolder;
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.recherche_activity_menu_item, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setQueryHint("Nom, Spécialité ou Ville");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
recherche(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recherche(newText);
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.recherche)
{
}
else if (item.getItemId()==R.id.filtrer)
{
FiltreDialog();
}
return super.onOptionsItemSelected(item);
}
private void FiltreDialog() {
String [] Options={"Spécialité", "Ville"};
AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
builder.setTitle("Afficher par:")
.setIcon(R.drawable.ic_sort_black_24dp)
.setItems(Options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,dbref.orderByChild("spécialité")) {
#Override
protected void populateViewHolder(ViewHolder
viewHolder, entreprises_class model, int position) {
viewHolder.details(getActivity(),
model.getNom(),model.getNum(), model.getSecteur(), model.getSpécialité(),
model.getVille(), model.getImage());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
else if(which==1){
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,dbref.orderByChild("ville")) {
#Override
protected void populateViewHolder(ViewHolder
viewHolder, entreprises_class model, int position) {
viewHolder.details(getActivity(),
model.getNom(),model.getNum(), model.getSecteur(), model.getSpécialité(),
model.getVille(), model.getImage());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
}
});
builder.show();
}
}
Over Here is my new Activity
public class entProfileFull extends AppCompatActivity {
Toolbar mtoolbar;
TextView textView, textView1, textView2, textView3, textView4;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ent_profile_full);
mtoolbar=findViewById(R.id.toolbar);
setSupportActionBar(mtoolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
textView=findViewById(R.id.nom_entreprise_full);
textView1=findViewById(R.id.secteur_entreprise_full);
textView2= findViewById(R.id.sp_entreprise_full);
textView3=findViewById(R.id.entreprise_ville);
textView4=findViewById(R.id.entreprise_num_full);
imageView=findViewById(R.id.entreprise_image_full);
byte[] bytes=getIntent().getByteArrayExtra("image");
String nom= getIntent().getStringExtra("nom");
String secteur= getIntent().getStringExtra("secteur");
String spécialité= getIntent().getStringExtra("spécialité");
String ville= getIntent().getStringExtra("ville");
String num= getIntent().getStringExtra("num");
Bitmap bm= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
textView.setText(nom);
textView1.setText(secteur);
textView2.setText(spécialité);
textView3.setText(ville);
textView4.setText(num);
imageView.setImageBitmap(bm);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is my ViewHolder Class
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView=itemView;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vclickListener.onItemClick(view, getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
vclickListener.onItemLongClick(view, getAdapterPosition());
return true;
}
});
}
public void details(Context cntx, String nom, String num, String secteur,
String spécialité,String ville, String image){
TextView textView= mView.findViewById(R.id.entreprise_nom);
TextView textView1= mView.findViewById(R.id.entreprise_secteur);
TextView textView2= mView.findViewById(R.id.entreprise_sous_secteur);
TextView textView3= mView.findViewById(R.id.entreprise_ville);
TextView textView4= mView.findViewById(R.id.entreprise_num);
ImageView imageView= mView.findViewById(R.id.entreprise_image);
textView.setText(nom);
textView1.setText(secteur);
textView2.setText(spécialité);
textView3.setText(ville);
textView4.setText(num);
Picasso.get().load(image).into(imageView);
}
private ViewHolder.ClickListener vclickListener;
public interface ClickListener{
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public void setOnClickListener(ViewHolder.ClickListener clickListener){
vclickListener = clickListener;
}
}
You shouldn't be calling itemView.setOnClickListener() from ViewHolder constructor. Because ViewHolder constructor is called from the onCreateViewHolder method. Henc you'll not have the position. So keep the itemView.setOnClickListener() methods inside onBindView() method
This will fix the issue
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 am trying to pass view Id from Recyclerview Adapter to Activity,when the Recycler view List item is clicked.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter{
public interface OnRecyclerItemClickListener {
void onRecyclerItemClick(User data,int id);
}
List<User> dataSource;
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private Context context;
public ActiveBeepsAdapter(List<User> dataArgs, OnRecyclerItemClickListener onRecyclerItemClickListener,Context context) {
this.dataSource = dataArgs;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_active_message, parent, false);
ViewHolder viewHolder = new ViewHolder(view, onRecyclerItemClickListener);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
User user = dataSource.get(position);
holder.tvId.setText(user.getId());
Picasso.with(context)
.load(user.getProfilePicUrl())
.placeholder(R.drawable.bg_logo)
.error(R.drawable.bg_logo)
.transform(new CircleTransform())
.into(holder.ivUserProfile);
}
#Override
public int getItemCount() {
return dataSource.size();
}
#NonNull
#Override
public String getSectionName(int i) {
return String.valueOf(dataSource.get(i).getId().charAt(0));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private OnRecyclerItemClickListener onRecyclerItemClickListener;
User data = new User();
TextView tvId;
ImageView ivUserProfile;
public ViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(itemView);
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
tvId = (TextView)itemView.findViewById(R.id.tvName);
ivUserProfile = (ImageView)itemView.findViewById(R.id.ivProfilePic);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,id);
}
}
}
Suppose, If the Profile Image is clicked, the view id should sent to activity..
And My Activity
#EActivity
public class ActiveMessage extends AppCompatActivity implements Adapter.OnRecyclerItemClickListener{
#ViewById(R.id.toolbar)
Toolbar toolbar;
#ViewById(R.id.rvactiveMessage)
FastScrollRecyclerView rvmessage;
List<User> allUser;
#ViewById(R.id.toolbar_title)
TextView tv_toolbar;
#AfterViews
protected void init(){
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_drop_down_black_24dp));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tv_toolbar.setText("Active Message");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
allUser = new ArrayList<>();
User user;
String fullName[] = {"ajay","kamal","akhil"};
String id[] = {"its_ajay","its_kamal","its_akhil"};
for(int i=0;i<id.length;i++){
user = new User();
user.setId(id[i]);
user.setFullName(fullName[i]);
allUser.add(user);
}
Adapter adapter = new Adapter(allUser,this,getApplicationContext());
rvmessage.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvmessage.setAdapter(activeBeepsAdapter);
}
#Override
public void onRecyclerItemClick(User data,int id) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (id == R.id.tvName){
Log.d("Id",data.getId());
}
}
public void noInternet(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.alert_dialog);
dialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_active_message);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
In my Activity, If the ProfileImage is clicked, pop up the dialog box.
Also, i need to check if there is Internet Connection when the list Item is clicked.
In adapter onClick method instead of id pass view:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,v);
}
Now in Activity
#Override
public void onRecyclerItemClick(User data,View view) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (view.getId() == R.id.tvName){
Log.d("Id",data.getId());
}
}
I want to take textview data from recycler view to another activity.I want to take
workshop_name TextView to Otheractivity.
Here is my code.
MechSearchActivity.java
public class MechSearchActivity extends AppCompatActivity {
List<SearchResponse.WorkshopDataBean> workshopList;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_mec);
recyclerView = (RecyclerView) findViewById(R.id.rv_workshoplist);
callSearchApi();
onItemClick();
}
public void callSearchApi() {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SearchResponse> call = apiService.getSearchData( "workshop_name","image", "street", "locality", "city"); // single search for all the values
call.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, retrofit2.Response<SearchResponse> response) {
SearchResponse searchResponse = response.body();
workshopList = searchResponse.getWorkshopData();
MechanicRecyclerAdapter adapter = new MechanicRecyclerAdapter(MechSearchActivity.this, workshopList);
recyclerView.setAdapter(adapter);
LinearLayoutManager mGridLayoutManager = new LinearLayoutManager(MechSearchActivity.this); // (Context context, int spanCount)
recyclerView.setLayoutManager(mGridLayoutManager);
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private void onItemClick() {
final GestureDetector mGestureDetector = new GestureDetector(MechSearchActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
recyclerView_ws.addOnItemTouchListener(new
RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildPosition(child);
String workshop_name = workshopList.get(position).getWorkshop_name();
Intent intent = new Intent(MechSearchActivity.this, OtherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("workshop_name", workshop_name);
startActivity(intent);
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
}
MechRecyclerAdapter.java
public class MechanicRecyclerAdapter extends RecyclerView.Adapter<MechanicRecyclerAdapter.MyViewHolder> {
private static final String TAG = MechanicRecyclerAdapter.class.getSimpleName();
Context mContext;
private LayoutInflater inflater;
String vehicle_type;
List<SearchResponse.WorkshopDataBean> workshopList;
public MechanicRecyclerAdapter(Context context, List<SearchResponse.WorkshopDataBean> workshopList) {
inflater = LayoutInflater.from(context);
this.workshopList = workshopList;
mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_workshop, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SearchResponse.WorkshopDataBean current = workshopList.get(position);
String ws_name = workshopList.get(position).getWorkshop_name();
holder.tv_workshopname.setText(ws_name);
}
#Override
public int getItemCount() {
return workshopList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
SearchResponse.WorkshopDataBean current;
TextView tv_workshopname;
public MyViewHolder(View itemView) {
super(itemView);
tv_workshopname = (TextView) itemView.findViewById(workshop_name);
}
}
}
OtherActivity.java
public class OtherActivity extends AppCompatActivity {
TextView SingleWorkshopName;
String workshop_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otheractivity);
SingleWorkshopName=(TextView)findViewById(R.id.single_workshop_name);
Bundle extras = getIntent().getExtras();
workshop_name = extras.getString("workshop_name", null);
}
}
For that you need to create one interface in your MechanicRecyclerAdapter
public interface OnListItemClick {
void onItemClick(int position);
}
in onBindViewHolder() assign your click by using following code
viewHolder.main_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onListItemClick.onItemClick(position);
}
});
Implements this interface in you MechSearchActivity you will get onItemClick() method in your activity using position you will get proper name of row and pass to other activity using intent.putExtra("workshop_name", workshop_name);