i am a newbie and i am trying to add some data in to the recyclerview from firbase db.but it showing the not serializable error. i searched everywhere and found couple of answers to make classes static and variables public but still not working, here are my codes
My Adapter
public class CardViewAdapter extends FirebaseRecyclerAdapter<MainpageCardModel,CardViewAdapter.Recyclerviewholder>{
public Context mcontext;
public List<MainpageCardModel> cakeslist;
public CardViewAdapter(DatabaseReference ref){
super(MainpageCardModel.class,R.layout.card,CardViewAdapter.Recyclerviewholder.cl ass,ref);
}
#Override
protected void populateViewHolder(Recyclerviewholder viewHolder, MainpageCardModel model, int position) {
viewHolder.ItemName.setText(MainpageCardModel.getItemName());
viewHolder.ItemPrice.setText(MainpageCardModel.getItemPrice());
if(MainpageCardModel.getItemImage() == null){
viewHolder.CardviewImageView.setImageDrawable(ContextCompat.getDrawable(mcontext,
R.drawable.ic_cake_dark));
}
else {
Glide.with(mcontext)
.load(MainpageCardModel.getItemImage())
.into(viewHolder.CardviewImageView);
}
}
public static class Recyclerviewholder extends RecyclerView.ViewHolder {
public ImageView CardviewImageView;
public TextView ItemName, ItemPrice;
public Recyclerviewholder(View itemView) {
super(itemView);
CardviewImageView = (ImageView) itemView.findViewById(R.id.cakepic_cardview);
ItemName = (TextView) itemView.findViewById(R.id.caketitle_cardview);
ItemPrice = (TextView) itemView.findViewById(R.id.cakeprice_cardview);
}
}
My model class
public Class MainpageCardModel{
public static String itemName;
public static String itemImage;
public static String itemPrice;
public MainpageCardModel(){
}
public MainpageCardModel(String itemName, String itemImage, String itemPrice){
this.itemImage=itemImage;
this.itemName=itemName;
this.itemPrice=itemPrice;
}
public static String getItemName() {
return itemName;
}
public void setItemName(String itemName){
this.itemName = itemName;
}
public static String getItemImage(){
return itemImage;
}
public void setItemImage(String itemImage){
this.itemImage= itemImage;
}
public static String getItemPrice(){
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
}
My Fragment
private static final String TAG = "FreshCreamFragment";
public static final String MENU_CHILD = "FreshCream";
private String Cakename, cakeprice, cakeurl;
private RecyclerView mRecyclerView;
private DatabaseReference mFirebaseDatabaseReference;
private CardViewAdapter adapterl;
private GridLayoutManager gridLayoutManager;
public List<MainpageCardModel> cakeslist;
ProgressBar mprogressbar;
MainpageCardModel mainpageCardModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cakeslist= new ArrayList<>();
adapterl = new CardViewAdapter(mFirebaseDatabaseReference.child(MENU_CHILD));
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("menu");
mFirebaseDatabaseReference.child(MENU_CHILD).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,String> cakedetails = (Map)dataSnapshot.getValue();
Cakename= cakedetails.get("Item_name");
cakeprice = cakedetails.get("Item_price");
cakeurl = cakedetails.get("url");
mainpageCardModel = new MainpageCardModel(Cakename,cakeurl,cakeprice);
cakeslist.add(mainpageCardModel);
adapterl.notifyDataSetChanged();
mprogressbar.setVisibility(ProgressBar.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fresh_cream_fragment, container, false);
mprogressbar = (ProgressBar) rootview.findViewById(R.id.progressBar3);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.freshcream_recyclerview);
gridLayoutManager = new GridLayoutManager(getContext(),2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mRecyclerView.setAdapter(adapterl);
return rootview;
}
}
MYdb
mydbscreenshot
looks like you have following lines in wrong order?
adapterl = new CardViewAdapter(mFirebaseDatabaseReference.child(MENU_CHILD));
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("menu");
Related
Please see the following issue:
All User Profile Images are not successfully displaying in the RecyclerView.
Text view is successfully displaying in the RecyclerView.
I looked up other similar issues online, but have not been able to find a solution.
I have updated my google play services, and my Firebase storage dependencies.
I am able to successfully pull the current user profile image in another activity.
I am getting the following 404 error message below:
**Adapter**
public class FindFriendsAdapter extends RecyclerView.Adapter<FindFriendsAdapter.FindFriendsViewHolder>
{
private Context context;
private List<FindFriendModel> findFriendModelList;
////This is a constructor and is a must have for recyclerviews/////
public FindFriendsAdapter(Context context, List<FindFriendModel> findFriendModelList) {
this.context = context;
this.findFriendModelList = findFriendModelList;
}
////This is a constructor and is a must have for recyclerviews/////
#NonNull
#Override
public FindFriendsAdapter.FindFriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.find_friends_layout, parent, false);
return new FindFriendsViewHolder(view); ///// layout converts our xml layout file to a programmable file some kind of way.
}
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
StorageReference fileref = FirebaseStorage.getInstance().getReference().child(Constants.IMAGES_FOLDER +"/" + friendModel.getProfileimage());
fileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(context)
.load(uri)
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}
});
}
#Override
public int getItemCount() {
return findFriendModelList.size();
}
public class FindFriendsViewHolder extends RecyclerView.ViewHolder{
private CircleImageView imageView_profile;
private TextView text_view_full_name;
private ImageButton button_request, button_cancel_request;
public FindFriendsViewHolder(#NonNull View itemView) {
super(itemView);
imageView_profile = itemView.findViewById(R.id.find_friends_profile_picture);
text_view_full_name = itemView.findViewById(R.id.find_friends_user_full_name);
button_request = itemView.findViewById(R.id.button_send_requests);
button_cancel_request = itemView.findViewById(R.id.button_cancel_requests);
}
}
}
**Model Class**
public class FindFriendModel
{
private String full_name;
private String profileimage;
private String userID;
private boolean requestSent;
public FindFriendModel(String full_name, String profileimage, String userID, boolean requestSent) {
this.full_name= full_name;
this.profileimage = profileimage;
this.userID = userID;
this.requestSent = requestSent;
}
public FindFriendModel() {}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public boolean isRequestSent() {
return requestSent;
}
public void setRequestSent(boolean requestSent) {
this.requestSent = requestSent;
}
}
**Fragment Java Class**
public class FindFriendsFragment extends Fragment {
private RecyclerView recycler_view_find_friends;
private FindFriendsAdapter findFriendsAdapter;
private List<FindFriendModel> findFriendModelList;
private TextView text_view_empty_Friends_List;
private DatabaseReference databaseReference;
private FirebaseUser currentUser;
public FindFriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_find_friends, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recycler_view_find_friends = view.findViewById(R.id.recycler_view_find_friends);
text_view_empty_Friends_List = view.findViewById(R.id.text_view_empty_find_friends);
recycler_view_find_friends.setLayoutManager(new LinearLayoutManager(getActivity()));
findFriendModelList = new ArrayList<>();
findFriendsAdapter = new FindFriendsAdapter(getActivity(), findFriendModelList);
recycler_view_find_friends.setAdapter(findFriendsAdapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = FirebaseAuth.getInstance().getCurrentUser();
text_view_empty_Friends_List.setVisibility(View.VISIBLE);
Query query = databaseReference.orderByChild("full_name");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
findFriendModelList.clear();
for (final DataSnapshot ds : dataSnapshot.getChildren())
{
final String userID = ds.getKey();
if (userID.equals(currentUser.getUid()))
return;
if (ds.child("full_name").getValue()!=null)
{
String fullName = ds.child("full_name").getValue().toString();
String profileImage = ds.child("profileimage").getValue().toString();
findFriendModelList.add(new FindFriendModel(fullName, profileImage, userID, false));
findFriendsAdapter.notifyDataSetChanged();
text_view_empty_Friends_List.setVisibility(View.GONE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(),"Failed to fetch friends", Toast.LENGTH_SHORT).show();
}
});
}
}
````
ds.child("full_name").getValue()!=null should be replaced by
Objects.equals(ds.child("full_name"), null)
It worked for me when I had the same error, maybe it will help you as well !
Figured out the issue:
The issue was that I was already saving my images images to Firebase Storage, and I was trying to get the download url string again.
I fixed the following part of my adapter:
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
Glide.with(context)
.load(friendModel.getProfileimage())
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}
Base on guideline at https://github.com/firebase/FirebaseUI-Android/tree/master/firestore, I make a list items with FirestoreRecyclerAdapter but I don't know why the couldn't retrieve any data. In fact, the number view items are shown correctly, but the content always null. Anyone can help me. Below is source code:
Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseFirestore mDatabase;
private ViewPager mViewPager;
private CollectionReference mOrderRef;
private OrderAdapter mOrderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_order_list);
mDatabase = FirebaseFirestore.getInstance();
mOrderRef = mDatabase.collection("order");
Query query = mOrderRef.limit(1000);
FirestoreRecyclerOptions<OrderInfo> options = new FirestoreRecyclerOptions.Builder<OrderInfo>().setQuery(query, OrderInfo.class).build();
mOrderAdapter = new OrderAdapter(options);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view_order_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mOrderAdapter);
}
#Override
protected void onStart() {
super.onStart();
mOrderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mOrderAdapter.stopListening();
}
Adapter:
public class OrderAdapter extends FirestoreRecyclerAdapter<OrderInfo, OrderAdapter.OrderHolder> {
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public OrderAdapter(#NonNull FirestoreRecyclerOptions<OrderInfo> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull OrderHolder holder, int position, #NonNull OrderInfo model) {
holder.txtTitle.setText(String.valueOf(model.getTitle()));
holder.txtCusName.setText(String.valueOf(model.getCusName()));
holder.txtDate.setText(String.valueOf(model.getDate()));
}
#NonNull
#Override
public OrderHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_item, parent, false);
return new OrderHolder(view);
}
class OrderHolder extends RecyclerView.ViewHolder{
TextView txtCusName;
TextView txtTitle;
TextView txtDate;
public OrderHolder(#NonNull View itemView) {
super(itemView);
txtCusName = itemView.findViewById(R.id.txt_customer_name);
txtTitle = itemView.findViewById(R.id.txt_title);
txtDate = itemView.findViewById(R.id.txt_date);
}
}
}
Data model:
public class OrderInfo {
private String mTitle;
private String mCusName;
private String mDate;
public OrderInfo(){
//default constructor
}
public OrderInfo(String title, String name, String date) {
this.mTitle = title;
this.mCusName = name;
this.mDate = date;
}
public String getTitle() {
return mTitle;
}
public String getCusName() {
return mCusName;
}
public void setCusName(String cusName) {
this.mCusName = cusName;
}
public String getDate() {
return mDate;
}
}
my database structure:
You data model is not aligned with database structure. Try to update it like below:
public class OrderInfo {
private String title;
private String name;
private String date;
public OrderInfo(){
//default constructor
}
public OrderInfo(String title, String name, String date) {
this.title = title;
this.name = name;
this.date = date;
}
public String getTitle() {
return title;
}
public String getName() {
return name;
}
public String getDate() {
return date;
}
}
Besides this don't forget to sync your project with firebase firestore.
I have recyclerview recieving data from firebase and i want to make last item uploaded to be first item in the list.I'm using GridLayoutManager and want to display a pic with a text, all of this work fine but i want to make them in order like instagram, does any one know something like that ?
Here is my code
public class ItemsUser extends Fragment {
private View mMainView;
private RecyclerView mUsersList;
private String user_id;
private DatabaseReference mUserDatabase;
private FirebaseRecyclerAdapter<ItemRecycleview,UserRecycleView> firebaseRecyclerAdapter;
private DatabaseReference mDatabaseReference;
private FirebaseListAdapter<ItemRecycleview> firebaseListAdapter;
public ItemsUser() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_items_user, container, false);
mUsersList = (RecyclerView) mMainView.findViewById(R.id.recyclerView_profile);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new GridLayoutManager(getActivity(),3));
ProfileUser activity = (ProfileUser) getActivity();
user_id = activity.getMyData();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users_photos").child(user_id);
mUserDatabase.keepSynced(true);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ItemRecycleview, UserRecycleView>(
ItemRecycleview.class,
R.layout.recycleview_item,
UserRecycleView.class,
mUserDatabase
) {
#Override
protected void populateViewHolder(UserRecycleView viewHolder, ItemRecycleview model, int position) {
viewHolder.setImageName(model.getImageName());
viewHolder.setImageURL(model.getImageURL(),getContext());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = firebaseRecyclerAdapter.getRef(mUsersList.getChildLayoutPosition(v)).getKey();
Intent imageIntent = new Intent(getActivity(), ImageActivity.class);
imageIntent.putExtra("imageKey",key);
imageIntent.putExtra("user_id",user_id);
startActivity(imageIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
public static class UserRecycleView extends RecyclerView.ViewHolder {
View mView;
public UserRecycleView(View itemView) {
super(itemView);
mView = itemView;
}
public void setImageName(String imageName){
TextView userNameView = (TextView) mView.findViewById(R.id.ImageNameTextView);
userNameView.setText(imageName);
}
public void setImageURL(final String imageURL,final Context ctx){
final ImageView userImageView = (ImageView) mView.findViewById(R.id.imageView);
Picasso.with(ctx).load(imageURL).networkPolicy(NetworkPolicy.OFFLINE).into(userImageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(imageURL).into(userImageView);
}
});
}
}
}
and this is ItemRecyclerview:
public class ItemRecycleview {
public String imageName;
public String imageURL;
public ItemRecycleview(){
}
public ItemRecycleview(String imageName, String imageURL) {
this.imageName = imageName;
this.imageURL = imageURL;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
}
hey guys i just found the answer :D
all you need to do is to add this method in firebaseRecyclerAdapter
here it's:
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ItemRecycleview, UserRecycleView>(
ItemRecycleview.class,
R.layout.recycleview_item,
UserRecycleView.class,
mUserDatabase
) {
#Override
public ItemRecycleview getItem(int position) {
return super.getItem(getItemCount() - 1 - position);
}
#Override
protected void populateViewHolder(UserRecycleView viewHolder, ItemRecycleview model, int position) {
viewHolder.setImageName(model.getImageName());
viewHolder.setImageURL(model.getImageURL(),getContext());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = firebaseRecyclerAdapter.getRef(mUsersList.getChildLayoutPosition(v)).getKey();
Intent imageIntent = new Intent(getActivity(), ImageActivity.class);
imageIntent.putExtra("imageKey",key);
imageIntent.putExtra("user_id",user_id);
startActivity(imageIntent);
}
});
}
};
and that will make it done
Have you tried using setReverseLayout() method to make first element last in the list
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(),3);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mUsersList.setLayoutManager(mLayoutManager);
First of all, Forgive me, my English is not good.
i have a RecyclerView with 9 items, But from the fourth item to the next, Pictures of the first 4 items are repeated for other items!
but other fields For all items in the RecyclerView, Have been completed correctly.
how to fix it problem?
this is my code:
My Model:
public class LocationsListModel {
final String DRAWABLE = "drawable/";
private String name,imageUrl, review, price;
public LocationsListModel(String name, String review, String price, String imageUrl) {
this.name = name;
this.review = review;
this.price = price;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public String getReview() {
return review;
}
public String getPrice() {
return price;
}
public String getImageUrl() {
return DRAWABLE + imageUrl;
}}
My Adapter:
public class LocationsListAdapter extends RecyclerView.Adapter<LocationsListAdapter.LocationsListView> {
private static ArrayList<LocationsListModel> locationList;
private Context context;
private ImageView locationImage;
public void setItems(ArrayList<LocationsListModel> items) {
this.locationList = items;
}
public class LocationsListView extends RecyclerView.ViewHolder {
public CardView cardView;
public TextView locationName;
public TextView review;
public TextView locationPrice;
public LocationsListView(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardView);
locationName = itemView.findViewById(R.id.location_name);
review = itemView.findViewById(R.id.review);
locationPrice = itemView.findViewById(R.id.price);
locationImage = itemView.findViewById(R.id.imageView2);
}
}
#Override
public LocationsListAdapter.LocationsListView onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.locations_list_item, parent, false);
context = parent.getContext();
return new LocationsListView(view);
}
#Override
public void onBindViewHolder(LocationsListAdapter.LocationsListView holder, int position) {
final LocationsListModel locationsListModel = locationList.get(position);
String uri = locationsListModel.getImageUrl();
int resource = locationImage.getResources().getIdentifier(uri, null, locationImage.getContext().getPackageName());
locationImage.setImageResource(resource);
holder.locationName.setText(locationsListModel.getName());
holder.review.setText(locationsListModel.getReview());
holder.locationPrice.setText(locationsListModel.getPrice());
}
#Override
public int getItemCount() {
return locationList.size();
}}
My Fragment:
public class LocationsListFragment extends Fragment {
private final LocationsListAdapter locationsListAdapter = new LocationsListAdapter();
private RecyclerView locationsList;
SimpleRatingBar ratingBar;
ArrayList<LocationsListModel> locationsListModels = new ArrayList<>();
public LocationsListFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static LocationsListFragment newInstance() {
LocationsListFragment fragment = new LocationsListFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_locations_list, container, false);
ratingBar = view.findViewById(R.id.ratingBar);
locationsList = view.findViewById(R.id.locations_lis);
setRecyclerViewItems();
return view;
}
private void setRecyclerViewItems() {
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(locationsList);
locationsList.setLayoutManager(new LinearLayoutManager(getContext(),
LinearLayoutManager.HORIZONTAL, true));
locationsList.setAdapter(locationsListAdapter);
locationsListModels.add(new LocationsListModel("Hotel 1","120 reviews","200$", "pic1"));
locationsListModels.add(new LocationsListModel("Hotel 2","102 reviews","120$", "pic2"));
locationsListModels.add(new LocationsListModel("Hotel 3","84 reviews","240$", "pic3"));
locationsListModels.add(new LocationsListModel("Hotel 4","113 reviews","220$", "pic4"));
locationsListModels.add(new LocationsListModel("Hotel 5","52 reviews","140$", "pic5"));
locationsListModels.add(new LocationsListModel("Hotel 6","57 reviews","190$", "pic6"));
locationsListModels.add(new LocationsListModel("Hotel 7","230 reviews","300$", "pic7"));
locationsListModels.add(new LocationsListModel("Hotel 8","131 reviews","90$", "pic8"));
locationsListModels.add(new LocationsListModel("Hotel 9","32 reviews","110$", "pic9"));
locationsListAdapter.setItems(locationsListModels);
locationsList.setHasFixedSize(true);
}}
You should use image in integer type -> R.drawable.p2
and your app/build.gradle add this :
compile 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
Your Model:
public class LocationsListModel {
public String name, review, price;
public int imageResource;
public LocationsListModel(String name, String review, String price, int imageResource) {
this.name = name;
this.review = review;
this.price = price;
this.imageResource = imageResource;
}
}
Your Adapter:
#Override
public void onBindViewHolder(LocationsListAdapter.LocationsListView holder, int position) {
LocationsListModel locationsListModel = locationList.get(position);
GlideApp.with(context).load(locationsListModel.imageResource)
.into(holder.imageView);
holder.locationName.setText(locationsListModel.name);
holder.review.setText(locationsListModel.review);
holder.locationPrice.setText(locationsListModel.price);
}
}
Your Fragment
locationsListModels.add(new LocationsListModel("Hotel 1","120 reviews","200$", R.drawable.pic1));
In Gradle:
compile 'com.github.bumptech.glide:glide:3.5.2'
Adapter:
Glide.with(context).load(imageurl).transform(new RoundImageTransform(context)).skipMemoryCache(true).into(ImageView);
Note : Remove RoundImageTransform -- It's for making an imageview as round in shape
In my code I am using an internet example that work fine using Retrofit2 and custom recyclerview but I decide to use this application in android starting at version 4.1.2 so the recyclerview doesn't work there. So, there is a possibility to change the custom recyclerview to a custom listview?
Lista_productos.java
public class Lista_productos extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<Elementos_fila_productos> elementos;
private RecyclerviewAdapter adapter;
private ApiInterface apiInterface;
static LayoutInflater layoutInflater;
static PopupWindow popupWindow;
static TextView nombre_seleccionado;
static FrameLayout frameLayout;
static String cantidad_deseada;
static char hola;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_productos);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview_tablillas);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
if(getIntent().getExtras() != null){
String type = getIntent().getExtras().getString("type");
buscarInformacion(type);
}
}
public void buscarInformacion(String type){
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<Elementos_fila_productos>> call = apiInterface.getElementosInfo(type);
call.enqueue(new Callback<List<Elementos_fila_productos>>() {
#Override
public void onResponse(Call<List<Elementos_fila_productos>> call, Response<List<Elementos_fila_productos>> response) {
elementos = response.body();
adapter = new RecyclerviewAdapter(elementos, Lista_productos.this);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<Elementos_fila_productos>> call, Throwable t) {
final AlertDialog.Builder builder = new AlertDialog.Builder(Lista_productos.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
builder.setCancelable(true);
builder.setTitle("Error!");
builder.setMessage("mensaje");
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
ListaComprasAdapter.java
public class ListaComprasAdapter extends BaseAdapter {
ArrayList<String> nombre;
ArrayList<String> cantidad;
ArrayList<String> precio;
ArrayList<String> total;
Context mContext;
//constructor
public ListaComprasAdapter(Context mContext, ArrayList<String> nombre, ArrayList<String> cantidad, ArrayList<String> precio, ArrayList<String> total) {
this.mContext = mContext;
this.nombre = nombre;
this.cantidad = cantidad;
this.precio = precio;
this.total = total;
}
public int getCount() {
return nombre.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View arg1, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.custom_lista_de_compras, viewGroup, false);
TextView Nombre = (TextView) row.findViewById(R.id.nombre_del_producto);
TextView Cantidad = (TextView) row.findViewById(R.id.cantidad);
TextView Precio = (TextView) row.findViewById(R.id.precio);
TextView Total = (TextView) row.findViewById(R.id.precio_total_producto);
Nombre.setText(nombre.get(position));
Cantidad.setText(cantidad.get(position));
Precio.setText(precio.get(position));
Total.setText(total.get(position));
return row;
}
}
Elementos_fila_productos.java : the elements of each row
public class Elementos_fila_productos {
#SerializedName("ID")
private String ID;
#SerializedName("Caracteristicas")
private String Caracteristicas;
#SerializedName("Precio")
private int Precio;
#SerializedName("Grosor")
private String Grosor;
#SerializedName("Disponibles")
private int Disponible;
#SerializedName("Imagen")
private String Imagen;
public String getGrosor() {
return Grosor;
}
public String getID() {
return ID;
}
public String getCaracteristicas() {
return Caracteristicas;
}
public int getPrecio() {
return Precio;
}
public int getDisponible() {
return Disponible;
}
public String getImagen() {
return Imagen;
}
}
ApiInterface.java
public interface ApiInterface {
#GET("tablillas2.php")
//revisar en el caso de que no funcione
Call<List<Elementos_fila_productos>> getElementosInfo(#Query("item_type") String item_type);
}
ApiClient.java
public class ApiClient {
public static final String Base_Url = "http://creadorjuancarloscfapptablilla.esy.es/appTablillas/";
public static Retrofit retrofit;
public static Retrofit getApiClient(){
if (retrofit==null){
retrofit = new Retrofit.Builder().baseUrl(Base_Url).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
It looks like RecyclerView does work for Android 4.1.2. See the accepted answer for this question: Would recyclerview work on an android device with Jellybean?