Android Studio & Firebase: CardView Loading Problem - java

I have a screen that shows my movie names and their pictures which are in my Firebase with CardView. Functionally, it works perfectly. But the problem is; firstly it shows the loadingPanel, secondly it shows the movie names, lastly it shows them with the pictures. Normally, it should show the loadingPanel until all names and pictures are shown.
My database's structure is like this. name is the string which is the name of my movie. profilePic is the string that contains the picture link from Firebase storage.
Where is my fault? Can you fix it?
Movies.java
package com.example.XXXX;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Movies extends AppCompatActivity {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Profile> list;
MyAdapter adapter;
private String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_films);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
reference = FirebaseDatabase.getInstance().getReference().child("Films");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<Profile>();
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Profile p = dataSnapshot1.getValue(Profile.class);
list.add(p);
}
adapter = new MyAdapter(Movies.this,list);
recyclerView.setAdapter(adapter);
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Movies.this,"Ooops... Something is wrong.",Toast.LENGTH_SHORT).show();
}
});
Intent intent = getIntent();
message = intent.getStringExtra("EXTRA_MESSAGE");
ImageButton backButton = (ImageButton) findViewById(R.id.imageButton13);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Movies.this, Menu.class);
i.putExtra("EXTRA_MESSAGE",message);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(Movies.this, Menu.class);
i.putExtra("EXTRA_MESSAGE",message);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
}
MyAdapter.java
package com.example.XXXX;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Profile> profiles;
public MyAdapter(Context c, ArrayList<Profile> p){
context = c;
profiles = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview,viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.name.setText(profiles.get(i).getName());
Picasso.get().load(profiles.get(i).getProfilePic()).into(myViewHolder.profilePic);
}
#Override
public int getItemCount() {
return profiles.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView name;
ImageView profilePic;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.film_name);
profilePic = (ImageView) itemView.findViewById(R.id.filmProfile);
}
}
}
Profile.java
package com.example.XXXX;
public class Profile {
private String name;
private String profilePic;
public Profile() {
}
public Profile(String name, String profilePic) {
this.name = name;
this.profilePic = profilePic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
}

According to your comments, I understand that you want to display a ProgessBar "until all names and pictures are settled and ready".
When you are using the following line of code in your onDataChange() method:
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
It means that you hide the ProgessBar when you finished getting the data from the database. What you have done till now, you only got the name and a reference (link) to the actual picture, not the picture itself. Since you already have the name, this is instantly displayed in your TextView, that's why you see it first. To display the actual image, it takes some time to download it and idsplay it in your ImageView using Picasso. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before the image is downloaded and displayed, that's why you see it delayed. This time depdends on the size of the image. To solve this, you have two options.
The first one would be to store a thumbnail of your actual image that has a small size and can be displayed almost instantly or you can attach a listener to each picture and display the entire view, only when the image is downloaded. I'm not familiar with Picasso but when using Glide for Android, you use RequestListener's onResourceReady() method.

Related

The data is getting stored in firebase real time database but the data is not getting displayed in the recycler view of the UI

I am new to android and I couldn't solve this issue. The terminal says that the string cannot be converted into purchasemodel.
But I am getting the data from purchasemodel only.
I don't know where the mistake is happening.
The data is getting stored in the realtime database but could not display in the recycler view UI.
Terminal error statements
com.google.firebase.database.DatabaseException: Can't convert object of type
java.lang.String to type com.example.books.purchasemodel
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.example.books.AdminBookDetails$2.onChildAdded(AdminBookDetails.java:99)
at com.google.firebase.database.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:79)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
AdminBookDetails.java
package com.example.books;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class AdminBookDetails extends AppCompatActivity implements
purchaseadapter.PurchaseClickInterface{
private RecyclerView booksRV;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private ConstraintLayout purchaseCL;
private purchaseadapter purchaseAdapter;
private Button Addbookdetails;
private Button Editbutton;
private RelativeLayout RLbottomsheet;
private ArrayList<purchasemodel> purchasemodelArrayList;
private FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_book_details);
getSupportActionBar().setTitle("Admin Book Details");
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
booksRV = findViewById(R.id.idRVpurchasebooks);
Addbookdetails = findViewById(R.id.Editdetails);
RLbottomsheet = findViewById(R.id.design_bottom_sheet);
//RLbottomsheet = findViewById(R.id.design_bottom_sheet);
firebaseDatabase = FirebaseDatabase.getInstance();
fAuth = FirebaseAuth.getInstance();
purchasemodelArrayList = new ArrayList<purchasemodel>();
databaseReference = firebaseDatabase.getReference("books");
Addbookdetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AdminBookDetails.this, admin_enterbookdetails.class);
startActivity(i);
}
});
//purchaseDbref = FirebaseDatabase.getInstance().getReference().child("Books");
//purchaseCL = findViewById(R.id.purchasebooksCL);
// we are initializing our adapter class and passing our arraylist to it.
purchaseAdapter = new purchaseadapter(purchasemodelArrayList,this,this::onCourseClick);
System.out.println("\n\narray passed\n\n");
// below line is for setting a layout manager for our recycler view.
// here we are creating vertical list so we will provide orientation as vertical
LinearLayoutManager linearLayoutManage = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
// in below two lines we are setting layoutmanager and adapter to our recycler view.
booksRV.setLayoutManager(linearLayoutManage);
booksRV.setAdapter(purchaseAdapter);
getAllBooks();
}
private void getAllBooks(){
purchasemodelArrayList.clear();
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
purchasemodelArrayList.add(snapshot.getValue(purchasemodel.class));
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCourseClick(int position) {
System.out.println("course clicked");
displaybottomsheetdialog(purchasemodelArrayList.get(position));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// on below line we are inflating our menu
// file for displaying our menu options.
getMenuInflater().inflate(R.menu.drawer_menu, menu);
return true;
}
private void displaybottomsheetdialog(purchasemodel Purchasemodel){
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
View layout = LayoutInflater.from(this).inflate(R.layout.bottomsheet, RLbottomsheet);
// setting content view for bottom sheet on below line.
bottomSheetDialog.setContentView(layout);
// on below line we are setting a cancelable
bottomSheetDialog.setCancelable(false);
bottomSheetDialog.setCanceledOnTouchOutside(true);
// calling a method to display our bottom sheet.
bottomSheetDialog.show();
TextView Booktitle = layout.findViewById(R.id.TVBooktitle);
TextView Author = layout.findViewById(R.id.TVauthor);
ImageView BookImg = layout.findViewById(R.id.IVbook);
TextView Publisher = layout.findViewById(R.id.TVPublisher);
//Button Editbutton = layout.findViewById(R.id.BtnEdt);
// Button Viewbutton = layout.findViewById(R.id.BtnView);
Booktitle.setText(Purchasemodel.getBook_title());
Author.setText(Purchasemodel.getAuthor_name());
//BookImg.setText(Purchasemodel.getBook_image());
Publisher.setText(Purchasemodel.getpublisher());
Picasso.get().load(Purchasemodel.getBook_image()).into(BookImg);
Editbutton = findViewById(R.id.BtnEdt);
Editbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AdminBookDetails.this, admin_editbookdetails.class);
// on below line we are passing our course modal
i.putExtra("books", Purchasemodel);
startActivity(i);
}
});

How to retrive Images from firestore to recyclerview

I am trying to retrieve images from Firebase Firestore. I am able to retrieve text in RecyclerView successfully however I'm not sure how to retrieve the images.
I had a look at similar questions unfortunately none helped.
My MainClass
package com.harsh.preacher.ui.HomeToDestination;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import com.harsh.preacher.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MustHaveEquipment extends AppCompatActivity {
DocumentSnapshot documentSnapshot;
RecyclerView recyclerView;
ArrayList<ProductModel> productModelArrayList ;
ProductAdapter productAdapter;
FirebaseFirestore db;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_must_have_equipment);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading Products");
progressDialog.show();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
db = FirebaseFirestore.getInstance();
productModelArrayList = new ArrayList<ProductModel>();
productAdapter = new ProductAdapter(MustHaveEquipment.this,productModelArrayList);
recyclerView.setAdapter(productAdapter);
EventChangeListner();
}
private void EventChangeListner() {
db.collection("Products")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable #org.jetbrains.annotations.Nullable QuerySnapshot value, #Nullable #org.jetbrains.annotations.Nullable FirebaseFirestoreException error) {
if(error!=null){
if(progressDialog.isShowing())
progressDialog.dismiss();
Log.e("No Internet Connection",error.getMessage());
}
for (DocumentChange dc : value.getDocumentChanges()){
if(dc.getType() == DocumentChange.Type.ADDED){
productModelArrayList.add(dc.getDocument().toObject(ProductModel.class));
}
productAdapter.notifyDataSetChanged();
if(progressDialog.isShowing())
progressDialog.dismiss();
}
}
});
}
}
My Adapter Class
package com.harsh.preacher.ui.HomeToDestination;
import android.content.Context;
import android.os.Build;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.FirebaseAppLifecycleListener;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.harsh.preacher.R;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import java.util.ArrayList;
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
DocumentSnapshot documentSnapshot;
Context context;
ArrayList<ProductModel> productModelArrayList;
public ProductAdapter(Context context, ArrayList<ProductModel> productModelArrayList) {
this.context = context;
this.productModelArrayList = productModelArrayList;
}
#NonNull
#NotNull
#Override
public ProductAdapter.ProductViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.epupiment_design,parent,false);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #NotNull ProductAdapter.ProductViewHolder holder, int position) {
ProductModel productModel = productModelArrayList.get(position);
holder.productName.setText(productModel.ProductName);
holder.aboutProduct.setText(productModel.AboutProduct);
holder.productDescription.setText(productModel.ProductUse);
}
#Override
public int getItemCount() {
return productModelArrayList.size();
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
TextView aboutProduct,productName,productDescription;
RelativeLayout expandable,card;
ImageView showmore,productImage;
public ProductViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
aboutProduct = itemView.findViewById(R.id.productDescription);
productName = itemView.findViewById(R.id.productName);
productDescription = itemView.findViewById(R.id.aboutProduct);
productImage = itemView.findViewById(R.id.productImage);
expandable = itemView.findViewById(R.id.expandable);
card = itemView.findViewById(R.id.cardeshwar);
showmore = itemView.findViewById(R.id.showMore);
showmore.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
if (expandable.getVisibility() == View.VISIBLE) {
TransitionManager.beginDelayedTransition(card,
new AutoTransition());
expandable.setVisibility(View.GONE);
showmore.setImageResource(R.drawable.showmore);
} else {
TransitionManager.beginDelayedTransition(card,
new AutoTransition());
expandable.setVisibility(View.VISIBLE);
showmore.setImageResource(R.drawable.showless);
}
}
});
}
}
}
My model class
package com.harsh.preacher.ui.HomeToDestination;
import android.widget.ImageView;
public class ProductModel {
String ProductName, ProductUse, AboutProduct;
ImageView ProductImage;
public ProductModel(){}
public ProductModel(String productName, String productUse, String aboutProduct,ImageView productImage){
ProductName = productName;
ProductUse = productUse;
AboutProduct = aboutProduct;
ProductImage = productImage;
}
public String getProductName() {
return ProductName;
}
public void setProductName(String productName) {
ProductName = productName;
}
public String getProductUse() {
return ProductUse;
}
public void setProductUse(String productUse) {
ProductUse = productUse;
}
public String getAboutProduct() {
return AboutProduct;
}
public void setAboutProduct(String aboutProduct) {
AboutProduct = aboutProduct;
}
public ImageView getProductImage() {
return ProductImage;
}
public void setProductImage(ImageView productImage) {
ProductImage = productImage;
}
}
Here is the structure of my database
Follow these steps to show images in RecyclerView
Remove ImageView from ProductModel
Add String imageUrl to ProductModel and set its value with the image URL from Firestore (I see from the screenshot that it is named "Image").
In onBindViewHolder from the ProductAdapter, use the position provided to retrieve the appropriate ProductModel from productModelArrayList and pass its imageUrl value to ProductViewHolder.
In ProductViewHolder, use the imageUrl to load the image into the ImageView. (Glide and Picasso are two commonly used library to load images)
PS: Never add UI elements in your model. It will cause lifecycle issues in the future.
Let me know if you have any questions.

How can I create new recycle views starting from a different recycle view on another activity

can anyone explain to me how can I create a new recycle and add items to that recycle view staring from another recycle view inside another activity?
Basically I want to create a shopping cart, for now, I retrieved the data from Firebase dataset and displayed it inside a recycle view but now I would like to send this data to the shopping cart(the shopping cart is inside another activity), I'm able to send the data but I can't understand how to display the data inside the new recycle view of this new activity. I need this because I want to see the items that I added to the shopping list so then I can pay.
Below I will attach a photo to explain myself better.
My problem is that I can't understand how to add the sent data to a recycle view again in the new activity.
I'm new to android so it's the first time I'm doing this thing.
Thank you in advance for your help.
My code:
SearchItemsActivity :
package com.example.ipill;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.List;
public class FirebaseSearch extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
String searchText="";
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
private static ArrayList<Users> arrayList = new ArrayList<>();
public static int cart_count = 0;
RecyclerView productRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firebasesearch);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");
mSearchField = findViewById(R.id.search_field);
mSearchBtn = findViewById(R.id.search_btn);
mResultList = findViewById(R.id.result_list_cart);
AddToCart = findViewById(R.id.imageButton2);
Cart = findViewById(R.id.cartButton);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
Cart.setOnClickListener(new View.OnClickListener() {
private Object Tag="Activity";
#Override
public void onClick(View v) {
if (cart_count < 1) {
} else {
startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
}
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery =
mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
String nome;
String surname;
Long prezzo;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart_count++;
Context context = v.getContext();
Intent intent = new Intent(context, CartActivity.class);
intent.putExtra("Name",nome);
intent.putExtra("Surname",surname);
intent.putExtra("Prezzo",Long.toString(prezzo));
context.startActivity(intent);
}
});
}
public void getDetails(String name,String cognome,Long price){
nome=name;
surname=cognome;
prezzo=price;
}
public void setDetails(String name, String surname, Long price) {
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
TextView user_price = (TextView)mView.findViewById(R.id.price);
user_name.setText(name);
user_surname.setText(surname);
user_price.setText(Long.toString(price));
}
}
}
enter code here
The second activity where I receive the data and where I want to create the recycle view
package com.example.ipill;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
public class CartActivity extends AppCompatActivity {
public static TextView grandTotal;
public static int grandTotalplus;
// create a temp list and add cartitem list
public static ArrayList<Users> temparraylist;
RecyclerView cartRecyclerView;
Button proceedToBook;
Context context;
String name,surname,price;
private static ArrayList<Users> arrayList2 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
context = this;
temparraylist = new ArrayList<>();
proceedToBook = findViewById(R.id.buyNow);
grandTotal = findViewById(R.id.TotalPrice);
cartRecyclerView=findViewById(R.id.cartList);
String passedArg = getIntent().getExtras().getString("Name");
name=passedArg;
String passedArg2 = getIntent().getExtras().getString("Surname");
surname=passedArg2;
String passedArg3 = getIntent().getExtras().getString("Price");
price=passedArg3;
System.out.println("DATA"+name+surname+price);
cartRecyclerView.setHasFixedSize(true);
cartRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
you can re use the cart adapter just implement a recylerView into new Activity and make the cart adater object and set it into the new reyclerView and it done

how do i make a recyclerview with data from firebase clickable with an intent

i am trying to write a code where data from firebase can be populated in recyclerview and also make it clickable so that it can pass the clicked data to a different activity anytime it is clicked
package com.example.helpresponse;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ShowStudentDetailsActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<StudentDetails> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_student_details);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(ShowStudentDetailsActivity.this));
progressDialog = new ProgressDialog(ShowStudentDetailsActivity.this);
progressDialog.setMessage("Loading Data from Firebase Database");
progressDialog.show();
databaseReference = FirebaseDatabase.getInstance().getReference("Police").child("Chats");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
StudentDetails studentDetails = dataSnapshot.getValue(StudentDetails.class);
list.add(studentDetails);
}
adapter = new RecyclerViewAdapter(ShowStudentDetailsActivity.this, list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
the above code displays the data from firebase being populated in recyclerview. but i want to make it clickable so that it will open a new activity that will pass the specific data that was clicked to the new activity.
package com.example.helpresponse;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class TargetDataAdapter extends RecyclerView.Adapter<TargetDataAdapter.TargetViewHolder>{
ArrayList<AndroidTargets> targetsArrayList;
public TargetDataAdapter(ArrayList<AndroidTargets> mTargetData) {
targetsArrayList = mTargetData;
}
#NonNull
#Override
public TargetViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.target_row,viewGroup,false);
return new TargetViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TargetViewHolder viewHolder, int i) {
viewHolder.androidTargetName.setText(targetsArrayList.get(i).FIELD1 );
viewHolder.androidTargetNumber.setText(String.format(Locale.getDefault(), "API Level: %d", targetsArrayList.get(i).FIELD2));
viewHolder.androidTargetShortName.setText(targetsArrayList.get(i).FIELD3);
}
#Override
public int getItemCount() {
if(targetsArrayList == null)
return 0;
return targetsArrayList.size();
}
public static class TargetViewHolder extends RecyclerView.ViewHolder {
protected TextView androidTargetName;
protected TextView androidTargetNumber;
protected TextView androidTargetShortName;
public TargetViewHolder(#NonNull View itemView) {
super(itemView);
androidTargetShortName= itemView.findViewById(R.id.textView2);
androidTargetName= itemView.findViewById(R.id.textView3);
androidTargetNumber= itemView.findViewById(R.id.textView4);
}
}
}
the above code is the recyclerview adapter
First Step : Create Interface with any name .
public interface HandleClick {
void onItemClick(int index);
}
after that : you need declare member variable of this interface in Adapter :
private HandleClick mHandleClick;
public void setmHandleClick(HandleClick handleClick) {
this.mHandleClick = handleClick;
}
after that : you need pass the actual implementation for this interface when declare adapter in main activity :
adapter = new RecyclerViewAdapter(ShowStudentDetailsActivity.this, list);
adapter.setmHandleClcik(new HandleClick() {
#Override
public void onItemClick(int index) {
// Here You can Add Any Java Code
Intent intent = new Intent(getApplicationContext() , TargetActivity.class);
startActivity(intent);
}
});
after that : you need trigger this Code when item click in recyclerView :
add this code in method onBindViewHolder :
myClickableView.setOnClickListener((v) -> {
mHandleClick.onItemClick(i);
});
This Way it's allow for developer use features of Activity it's host The recycler View as :
1- startAactivityForResult
2- if you use pagination in your request you can make new request from activity not adapter .
You can set up a clickable view in onBindViewHolder and pass your data in the intent. Something like this:
Add a context field to your TargetDataAdapter class:
private Context context;
Assign the context in onCreateViewHolder:
context = viewGroup.getContext();
Set up the clickable view and pass it an intent with your data:
#Override
public void onBindViewHolder(#NonNull TargetViewHolder viewHolder, int i) {
viewHolder.androidTargetName.setText(targetsArrayList.get(i).FIELD1 );
viewHolder.androidTargetNumber.setText(String.format(Locale.getDefault(), "API Level: %d", targetsArrayList.get(i).FIELD2));
viewHolder.androidTargetShortName.setText(targetsArrayList.get(i).FIELD3);
View myClickableView = viewHolder.itemView.findViewById(R.id.my_clickable_view);
myClickableView.setOnClickListener((v) -> {
Intent intent = new Intent(context, MyClassIWantToSendDataTo.class);
intent.putExtra("myDataKey", myData);
//more intent.putExtra(s) as needed
context.startActivity(intent);
});
}

Adding items in RecyclerView from the data that comes from an intent not behaving properly

Adding items in RecyclerView from the data that comes from an intent that brings the data from another activity not behaving as expected.
This is the Main Activity of the app:
package com.example.android.contacts;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
RecyclerView contactListView;
private ViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent2 = getIntent();
String nameTxt = intent2.getStringExtra("ContactName");
String phoneTxt = intent2.getStringExtra("PhoneNumber");
String emailTxt = intent2.getStringExtra("Email");
String addressTxt = intent2.getStringExtra("Address");
contactListView = (RecyclerView) findViewById(R.id.listView);
getData(nameTxt,phoneTxt,emailTxt,addressTxt);
adapter = new ViewAdapter(getApplication(), getData(nameTxt,phoneTxt,emailTxt,addressTxt));
contactListView.setAdapter(adapter);
}
public List<Contact> getData(String name, String phone, String email, String address){
List<Contact> data = new ArrayList<>();
data.add(new Contact(name,phone,email,address));
return data;
}
public void addNewContact (View view){
Intent intent = new Intent (Main2Activity.this, MainActivity.class);
startActivity(intent);
}
}
This is the Adapter :
package com.example.android.contacts;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder>{
private LayoutInflater inflator;
List<Contact> data = Collections.emptyList();
public ViewAdapter (Context context, List<Contact> data){
inflator=LayoutInflater.from(context);
this.data=data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
holder.name.setText(current.getName());
holder.phone.setText(current.getPhone());
holder.email.setText(current.getEmail());
holder.address.setText(current.getAddress());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView name;
TextView phone;
TextView email;
TextView address;
public MyViewHolder(View itemView) {
super(itemView);
name=(TextView) itemView.findViewById(R.id.contactName);
phone=(TextView) itemView.findViewById(R.id.phoneNumber);
email=(TextView) itemView.findViewById(R.id.emailAddress);
address=(TextView) itemView.findViewById(R.id.cAddress);
}
}
}
The activity gets the data from another activity and the data comes into the main activity utilizing an intent, and the part of data receiving to the main activity is tested and works as expected.
This is the activity that feeds the data to the main Activity:
package com.example.android.contacts;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
}
public void addContact (View view){
if (nameTxt.getText().length()==0){
nameTxt.setError("Please enter the Name");
}
else if (phoneTxt.getText().length()==0){
phoneTxt.setError("Please enter the Phone Number");
}
else if (emailTxt.getText().length()==0){
emailTxt.setError("Please enter the Email");
}
else if (addressTxt.getText().length()==0){
addressTxt.setError("Please enter the Address");
}
else{
Intent intent = new Intent (this, Main2Activity.class);
intent.putExtra("ContactName",nameTxt.getText().toString());
intent.putExtra("PhoneNumber",phoneTxt.getText().toString());
intent.putExtra("Email",emailTxt.getText().toString());
intent.putExtra("Address",addressTxt.getText().toString());
startActivity(intent);
}
}
}
It´s a simple thing but I want to show you, what the problem is. I guess you are not understanding what we want to explain in the comments. No problem, everybody has started off small (like we say in Germany) :). So here is your problem:
public List<Contact> getData(String name, String phone, String email, String address){
List<Contact> data = new ArrayList<>();
//data.add(new Contact(name,phone,email,address));
return data;
}
The two slashes // means that you have commented the code out. So it is not active anymore. To add these values to your list, you have to remove that slashes. It must look like this:
public List<Contact> getData(String name, String phone, String email, String address){
List<Contact> data = new ArrayList<>();
data.add(new Contact(name,phone,email,address));
return data;
}
Do you see the difference? Also here in that post, in your example, it´s grayed out...

Categories

Resources