i have this issue that i am trying to solve without success. i created an pp that shows a recyclerview on main activity. But when the app is launched for the very first time the recyclerview is empty though i am fetching data from firestore, but when i go another activity and come back it get loaded. i am using AsyncTask here is my code
public class FragmentHome extends Fragment {
private List<ProductPost> product_list;
private RecyclerAdapter productRecyclerAdapter;
FirebaseFirestore firebaseFirestore;
RecyclerView product_list_view;
public FragmentHome() {
// Required empty public constructor
}
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
//initialize AsynTask class
LoadMyData loadMyData = new LoadMyData(getContext());
loadMyData.execute();
View view = inflater.inflate(R.layout.fragment_fragment_home,
container, false);
//product list for adapters
product_list = new ArrayList<>();
product_list_view = view.findViewById(R.id.recycler1);
productRecyclerAdapter = new RecyclerAdapter(getActivity(), product_list);
product_list_view.setLayoutManager(new
LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
product_list_view.setAdapter(productRecyclerAdapter);
}
public class LoadMyData extends AsyncTask<String, String, String>{
private Context context;
private ProgressDialog progressDialog;
public LoadMyData(Context context){
this.context = context;
}
#Override
protected String doInBackground(String... strings) {
//Retrieve politics books for recycler1
Query secondQuery = firebaseFirestore.collection("All_Books")
.whereEqualTo("category", "politics")
.orderBy("time", Query.Direction.DESCENDING);
secondQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
if(queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()){
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String productID = doc.getDocument().getId();
ProductPost productPost = doc.getDocument().toObject(ProductPost.class).withId(productID);
product_list.add(productPost);
productRecyclerAdapter.notifyDataSetChanged();
}
}
}//else statement here...
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
product_list_view.setAdapter(productRecyclerAdapter);
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading data...");
progressDialog.show();
super.onPreExecute();
}
}
}
//getter and setter class
package com.example.ibrahimsahko.yateerenlite;
import java.util.Date;
public class ProductPost extends ProductID{
private String Name, book_price, book_title, image, category;
private Date time;
private String qty;
public ProductPost(){
}
public ProductPost(String name, String book_price, String book_title, String image, Date time, String category, String qty) {
this.Name = name;
this.book_price = book_price;
this.book_title = book_title;
this.image = image;
this.time = time;
this.category = category;
this.qty = qty;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBook_price() {
return book_price;
}
public void setBook_price(String book_price) {
this.book_price = book_price;
}
public String getBook_title() {
return book_title;
}
public void setBook_title(String book_title) {
this.book_title = book_title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
}
I will be gratefull if anyone can help me find whats wrong with m code here
You can be in post you are passing the adapter again when you already have it on the onCreateView
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
//product_list_view.setAdapter(productRecyclerAdapter);
super.onPostExecute(s);
}
Related
Idk why is it not working, Im trying to transfer data, i'm doing an app but when i run it i get an error, the Error is in the BlogActivity Class
"showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));"(java.lang.NullPointerException).
This is BlogActivity Class:
public class BlogActivity extends AppCompatActivity{
private static final String EXTRAS_BLOG = "EXTRAS_BLOG";
private TextView textTitle;
private TextView textDate;
private TextView textAuthor;
private TextView textRating;
private TextView textDescription;
private TextView textViews;
private RatingBar ratingBar;
private ImageView imageAvatar;
private ImageView imageMain;
private ImageView imageBack;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogpage);
imageMain = findViewById(R.id.yemenImg);
imageAvatar = findViewById(R.id.yemenAvatar);
imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent myInt = new Intent(getApplicationContext(),MainActivity.class);
startActivity(myInt);
}
},2);
}
});
textDate = findViewById(R.id.dateYemen);
textTitle = findViewById(R.id.textTitle);
textAuthor = findViewById(R.id.yemenAuthor);
textRating = findViewById(R.id.textRating);
textViews = findViewById(R.id.textViews);
textDescription = findViewById(R.id.textDescription);
ratingBar = findViewById(R.id.ratingBar);
progressBar = findViewById(R.id.progressBar);
showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));
}
/*private void loadData()
{
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showData(blogList.get(0));
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
showErrorSnackbar();
}
});
}
});
}*/
private void showData(Blog blog)
{
progressBar.setVisibility(View.GONE);
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
textAuthor.setText(blog.getAuthor().getName());
textRating.setText(String.valueOf(blog.getRating()));
textViews.setText(String.format("(%d views)", blog.getViews()));
textDescription.setText(blog.getDescription());
textDescription.setText(Html.fromHtml(blog.getDescription(),Html.FROM_HTML_MODE_COMPACT));
ratingBar.setRating(blog.getRating());
ratingBar.setVisibility(View.VISIBLE);
imageBack.setImageResource(R.drawable.ic_baseline_arrow_back_24);
Glide.with(this)
.load(blog.getImage())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageMain);
Glide.with(this)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
/*private void showErrorSnackbar()
{
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
snackbar.dismiss();
});
snackbar.show();
}*/
public static void startBlogDetailsActivity(Activity activity, Blog blog) {
Intent intent = new Intent(activity, BlogActivity.class);
intent.putExtra(EXTRAS_BLOG, blog);
activity.startActivity(intent);
}
Blog Class:
public class Blog implements Parcelable {
private String id;
private Author author;
private String title;
private String date;
private String image;
private String description;
private int views;
private float rating;
protected Blog(Parcel in) {
id = in.readString();
title = in.readString();
date = in.readString();
image = in.readString();
description = in.readString();
views = in.readInt();
rating = in.readFloat();
author = in.readParcelable(Author.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(date);
dest.writeString(image);
dest.writeString(description);
dest.writeInt(views);
dest.writeFloat(rating);
dest.writeParcelable(author, 0);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Blog> CREATOR = new Creator<Blog>() {
#Override
public Blog createFromParcel(Parcel in) {
return new Blog(in);
}
#Override
public Blog[] newArray(int size) {
return new Blog[size];
}
};
public String getTitle() {
return title;
}
public String getDate() {
return date;
}
public String getImage() {
return image;
}
public String getDescription() {
return description;
}
public int getViews() {
return views;
}
public float getRating() {
return rating;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Blog blog = (Blog) o;
return views == blog.views &&
Float.compare(blog.rating, rating) == 0 &&
Objects.equals(id, blog.id) &&
Objects.equals(author, blog.author) &&
Objects.equals(title, blog.title) &&
Objects.equals(date, blog.date) &&
Objects.equals(image, blog.image) &&
Objects.equals(description, blog.description);
}
#Override
public int hashCode() {
return Objects.hash(id, author, title, date, image, description, views, rating);
}
This is Main Activity Class:
public class MainActivity extends AppCompatActivity {
private MainAdapter adapter;
private SwipeRefreshLayout refreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainAdapter(blog ->
BlogActivity.startBlogDetailsActivity(this, blog));
RecyclerView recyclerView = findViewById(R.id.recylerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
refreshLayout = findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(this::loadData);
loadData();
}
private void loadData()
{
refreshLayout.setRefreshing(true);
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
adapter.submitList(blogList);
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
showErrorSnackbar();
}
});
}
});
}
private void showErrorSnackbar() {
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
loadData();
snackbar.dismiss();
});
snackbar.show();
}
This is MainAdapter Class:
public class MainAdapter extends ListAdapter<Blog, MainAdapter.MainViewHolder>{
public interface OnItemClickListener{
void onItemClicked(Blog blog);
}
private OnItemClickListener clickListener;
public MainAdapter(OnItemClickListener clickListener){
super(DIFF_CALLBACK);
this.clickListener = clickListener;
}
#NonNull
#Override
public MainAdapter.MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_listlayout,parent,false);
return new MainViewHolder(view, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.MainViewHolder holder, int position)
{
holder.bindTo(getItem(position));
}
static class MainViewHolder extends RecyclerView.ViewHolder
{
private TextView textTitle;
private TextView textDate;
private ImageView imageAvatar;
private Blog blog;
public MainViewHolder(#NonNull View itemView, OnItemClickListener listener)
{
super(itemView);
itemView.setOnClickListener(view -> listener.onItemClicked(blog));
textTitle = itemView.findViewById(R.id.textTitle);
textDate = itemView.findViewById(R.id.textDate);
imageAvatar = itemView.findViewById(R.id.imageAvatar);
}
void bindTo(Blog blog)
{
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
Glide.with(itemView)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
}
private static final DiffUtil.ItemCallback<Blog> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Blog>()
{
#Override
public boolean areItemsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.getId().equals(newItem.getId());
}
#Override
public boolean areContentsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.equals(newItem);
}
};
You may set value to blog variable in MainViewHolder.
Add this line to your bindTo() method body:
this.blog = blog
I'm referring this tutorial ==> https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/ in my project I have bottom navigation...I am trying to add favourites in the first tab and displaying favourites in the second tab in the bottom navigation bar. I'm using Room library.
When activity loads favourites are all blank at first, but when I first row as favourite and go-to favourite tab it displays properly but when I came back to the first tab it fills all the favourites icon automatically (which I have not done I had only done the first row)
Really need help. Thanks in advance.
Dao:
#Dao
public interface FavoriteDao {
#Insert
public void addData(FavoriteList favoriteList);
#Query("select * from favoritelist")
public List<FavoriteList> getFavoriteData();
#Query("SELECT EXISTS (SELECT 1 FROM favoritelist WHERE id=:id)")
public int isFavorite(int id);
#Delete
public void delete(FavoriteList favoriteList);
}
Database:
#Database(entities={FavoriteList.class},version = 1)
public abstract class FavoriteDatabase extends RoomDatabase {
public abstract FavoriteDao favoriteDao();
}
FavoriteList:
#Entity(tableName="favoritelist")
public class FavoriteList {
#PrimaryKey
private int id;
#ColumnInfo(name = "source")
private String source;
#ColumnInfo(name = "author")
private String author;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "description")
private String description;
#ColumnInfo(name = "url")
private String url;
#ColumnInfo(name = "urlToImage")
private String urlToImage;
#ColumnInfo(name = "publishedAt")
private String publishedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
News fragment:
public class news extends Fragment {
ImageView favbtn;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
Adapter adapter;
List<Articles> articles = new ArrayList<>();
public static FavoriteDatabase favoriteDatabase;
public news() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news, container, false);
swipeRefreshLayout = view.findViewById(R.id.swiprefresh);
etQuery = view.findViewById(R.id.etQuery);
btnSearch = view.findViewById(R.id.btnSearch);
favoriteDatabase= Room.databaseBuilder(getActivity(),FavoriteDatabase.class,"myfavdb").
allowMainThreadQueries().build();
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final String country = getCountry();
retrieveJson("", country, API_Key);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")) {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(), country, API_Key);
}
});
retrieveJson(etQuery.getText().toString(), country, API_Key);
} else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson("", country, API_Key);
}
});
retrieveJson("", country, API_Key);
}
}
});
return view;
}
private void showChangeLanguageDialog() {
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!etQuery.getText().toString().equals("")) {
call = ApiClient.getInstance().getApi().getSpecifiedData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
// articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final Adapter.ViewHolder holder, final int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
Picasso.get().load(imageUrl).into(holder.imageView);
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(dateTime(a.getPublishedAt()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailedActivity.class);
intent.putExtra("title",a.getTitle());
intent.putExtra("source",a.getSource().getName());
intent.putExtra("time",dateTime(a.getPublishedAt()));
intent.putExtra("desc",a.getDescription());
intent.putExtra("imageUrl",a.getUrlToImage());
intent.putExtra("url",a.getUrl());
context.startActivity(intent);
}
});
if (news.favoriteDatabase.favoriteDao().isFavorite(articles.get(position).getId())==1)
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
else
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FavoriteList favoriteList = new FavoriteList();
int id = articles.get(position).getId();
String source = articles.get(position).getSource().getName();
String author = articles.get(position).getAuthor();
String publishedAt = articles.get(position).getPublishedAt();
String description = articles.get(position).getDescription();
String title = articles.get(position).getTitle();
String url = articles.get(position).getUrl();
String urlToImage = articles.get(position).getUrlToImage();
favoriteList.setId(id);
favoriteList.setAuthor(author);
favoriteList.setDescription(description);
favoriteList.setSource(source);
favoriteList.setPublishedAt(publishedAt);
favoriteList.setTitle(title);
favoriteList.setUrl(url);
favoriteList.setUrlToImage(urlToImage);
favoriteList.setPublishedAt(dateTime(articles.get(position).getPublishedAt()));
if (news.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
news.favoriteDatabase.favoriteDao().addData(favoriteList);
}else {
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
news.favoriteDatabase.favoriteDao().delete(favoriteList);
}
}
});
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate;
ImageView imageView;
ImageButton bookmark;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvId);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
bookmark = itemView.findViewById(R.id.favrr);
}
}
Steps to debug:
Add 2-3 items as Favs.
Restart the Application.
Check if it shows those items as fav after restarting application .
also add logs to those if conditions where you are changing the drawables.
After looking at your JSON it looks like id is what creating problems. Id is null for all your json items so when fav. one it shows fav. to all.
Solution : Use another field to check if the data is added to fav.list
Delete will not work either
Try
#Query("DELETE FROM favoritelist WHERE title = :title")
void deleteByUserId(String title);
To delete item
Also https://github.com/amitshekhariitbhu/Android-Debug-Database
check this library to debug your database
My RecyclerView not show any data from Firebase. I don't see any errors at logcat so I don't know why. I followed guide from youtube video. But still nothing. I'm using android 8.0 and API 27. Hope Somebody can help.
My Main Activity Code:
public class ViewProduct extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Model> list;
private RecyclerView recyclerView;
private RecyclerView.Adapter viewHolder;
private RecyclerView.LayoutManager layoutManager;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product) ;
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
recyclerView = findViewById(R.id.stallproductRecyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//SEARCH VIEW
searchView = findViewById(R.id.searchProductStall);
//ADAPTER
list = new ArrayList<>();
viewHolder = new ViewHolder(list);
recyclerView.setAdapter(viewHolder);
}
#Override
protected void onRestart() {
super.onRestart();
if (ref!=null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
//list = new ArrayList<>();
list.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Model.class));
}
//ViewHolder viewHolder = new ViewHolder(list);
//recyclerView.setAdapter(viewHolder);
viewHolder.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ViewProduct.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
if (searchView !=null)
{
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
private void search(String str) {
ArrayList<Model> myList = new ArrayList<>();
for(Model object : list)
{
if(object.getProductName().toLowerCase().contains(str.toLowerCase()))
{
myList.add(object);
}
}
ViewHolder viewHolder = new ViewHolder(myList);
recyclerView.setAdapter(viewHolder);
}
}
My Adapter:
public class ViewHolder extends RecyclerView.Adapter<ViewHolder.MyViewHolder> {
ArrayList<Model> list;
public ViewHolder (ArrayList<Model> list)
{
this.list=list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_product, viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.productName.setText(list.get(i).getProductName());
myViewHolder.productCalorie.setText(list.get(i).getProductCalorie());
myViewHolder.StallId.setText(list.get(i).getStallId());
myViewHolder.productType.setText(list.get(i).getProductType());
myViewHolder.productServing.setText(list.get(i).getProductServing());
myViewHolder.statusProduct.setText(list.get(i).getStatusProduct());
}
#Override
public int getItemCount()
{
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView productName, productCalorie, StallId;
TextView productType, productServing, statusProduct;
ImageView productImageView;
public MyViewHolder (#NonNull View itemView){
super((itemView));
productName = itemView.findViewById(R.id.productTitle);
productCalorie = itemView.findViewById(R.id.productDescriptionCalorie);
StallId = itemView.findViewById(R.id.productDescriptionStallId);
productType = itemView.findViewById(R.id.productDescriptionType);
productServing=itemView.findViewById(R.id.productDescriptionServing);
statusProduct=itemView.findViewById(R.id.productDescriptionAvailibility);
//productImageView = itemView.findViewById(R.id.productImageView);
}
}
}
My Model :
package com.example.buddymealplannerstall.Child;
import android.view.Display;
public class Model {
//String productName, productImage, productCalorie, StallId, productType, productServing, statusProduct;
private String StallId;
private String productCalorie;
private String productImage;
private String productName;
private String productServing;
private String productType;
private String statusProduct;
public Model (String StallId,
String productCalorie,
String productImage,
String productName,
String productServing,
String productType,
String statusProduct){
this.StallId = StallId;
this.productCalorie = productCalorie;
this.productImage = productImage;
this.productName = productName;
this.productServing = productServing;
this.productType = productType;
this.statusProduct = statusProduct;
}
public Model(){
}
public String getStallId() {
return StallId;
}
public void setStallId(String stallId) {
StallId = stallId;
}
public String getProductCalorie() {
return productCalorie;
}
public void setProductCalorie(String productCalorie) {
this.productCalorie = productCalorie;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductServing() {
return productServing;
}
public void setProductServing(String productServing) {
this.productServing = productServing;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getStatusProduct() {
return statusProduct;
}
public void setStatusProduct(String statusProduct) {
this.statusProduct = statusProduct;
}
}
Screen Shot of my firebase and my apps.
firebase
my app
According to your comment:
yes, buddymealplanner is my project's name
Please note that there is no need to add the name of your project as a child in the reference. So please change the following line of code:
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
Simply to:
ref = FirebaseDatabase.getInstance().getReference().child("Products");
I dont think you are populating your list, you are sending it empty. From what I can see, you only add items to the list when you are restarting the activity. Try either populating it before sendinig the list, or changing the onRestart() for an onStart() or an onResume().
I can't understand why it makes problem with it. It take data from server with retrofit and it can't use that data in recyclerview. It make problem with Constructor but I can not understand why it makes problem with it. That can get data from service successfully with this Model, but problem is to put adapter and recyclierview. How can solve it?
ProductPage.java
public class ProductPage {
private int productID;
private String productName;
private String productDescription;
private List<String> productImages;
private List<ProductPrice> productPrices;
public int getProductID() {
return productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public List<String> getProductImages() {
return productImages;
}
public void setProductImages(List<String> productImages) {
this.productImages = productImages;
}
public List<ProductPrice> getProductPrices() {
return productPrices;
}
public void setProductPrices(List<ProductPrice> productPrices) {
this.productPrices = productPrices;
}
}
ProductDetailAdapter.java
public class ProductDetailAdapter extends RecyclerView.Adapter<ProductDetailAdapter.ViewHolder> {
private Context mContext;
int rawLayout;
private List<ProductPage> productPageList;
private int cartAmount;
public ProductDetailAdapter(Context mContext,int rawLayout, List<ProductPage> productPageList, CartListener cartListener) {
this.mContext = mContext;
this.rawLayout = rawLayout;
this.productPageList = productPageList;
this.cartListener = cartListener;
}
#NonNull
#Override
public ProductDetailAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View mView = LayoutInflater.from(parent.getContext()).inflate(rawLayout, parent, false);
return new ViewHolder(mView); }
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
Glide.with(mContext).load(productPageList.get(position).getProductPrices().get(position).getShopImage())
.apply(RequestOptions.placeholderOf(R.drawable.ic_glide_img).error(R.drawable.ic_glide_warning)).
into(viewHolder.imgProductDetail);
viewHolder.textProductDetailCost.setText(Double.toString(productPageList
.get(position).getProductPrices().get(position).getShopProductPrice())+" TL");
viewHolder.textProductDetailMarket.setText(productPageList.get(position).getProductPrices().get(position).getShopName());
}
#Override
public int getItemCount() {
return productPageList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imgProductDetail;
private TextView textProductDetailCost, textProductDetailMarket;
private Button btnProductDetail;
private CardView cardViewProductDetail;
ViewHolder(View itemView){
super(itemView);
imgProductDetail = itemView.findViewById(R.id.imageView_product_detail);
textProductDetailCost = itemView.findViewById(R.id.text_product_detail_cost);
textProductDetailMarket = itemView.findViewById(R.id.textViewProductShopName);
btnProductDetail = itemView.findViewById(R.id.buttonProductDetail);
cardViewProductDetail = itemView.findViewById(R.id.cardViewProductDetail);
}
}
public interface CartListener {
void onProductSelect(ProductPage productPage);
}
}
ProductActivity.java
public class ProductActivity extends AppCompatActivity implements ProductDetailAdapter.CartListener {
TextView textProductName, textDescription;
RecyclerView recyclerViewProduct;
protected RecyclerView.LayoutManager mLayoutManager;
String productCost, productMarket, productImage, productTitle, prdouctMarketImage;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
init();
loadProductPage();
}
private void init() {
textProductName = findViewById(R.id.text_product_title);
imgProduct = findViewById(R.id.img_product);
recyclerViewProduct = findViewById(R.id.product_recycylerwiew);
textDescription = findViewById(R.id.text_product_description);
textDescription.setMovementMethod(new ScrollingMovementMethod()); // Scroll yapabilmek için açmıştım
mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewProduct.setLayoutManager(mLayoutManager);
private void loadProductPage() {
ApiInterface apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<ProductPage> call = apiInterface.getProductPage(id);
call.enqueue(new Callback<ProductPage>() {
#Override
public void onResponse(Call<ProductPage> call, Response<ProductPage> response) {
if (response.isSuccessful()) {
ProductPage product_page_list = response.body();
textProductName.setText(product_page_list.getProductName());
textDescription.setText(product_page_list.getProductDescription());
Glide.with(getApplicationContext()).load(product_page_list.getProductImages())
.apply(RequestOptions.placeholderOf(R.drawable.ic_glide_img).error(R.drawable.ic_glide_warning)).
into(imgProduct);
ProductDetailAdapter myAdapter = new ProductDetailAdapter(getApplicationContext(),R.layout.product_detail_item_view,product_page_list,ProductActivity.this);
recyclerViewProduct.setAdapter(myAdapter);
}
else
ApiErrorUtils.parseError(response);
}
#Override
public void onFailure(Call<ProductPage> call, Throwable t) {
Log.d("response","apiError");
}
});
}
#Override
public void onProductSelect(ProductPage productPage) {
}
You are just passing ProductPage object to adapter.
ProductPage product_page_list = response.body();
but your adapter required
List<ProductPage> productPageList
So you need to add product object to product list like this
ProductPage productPage = response.body();
List<ProductPage> productList=new ArrayList<>();
productList.add(productPage);
ProductPage product_page_list = response.body();
product_page_list is not List<ProductPage>()
in your adapter need List<ProductPage> productPageList
This is my adapter class , where taking setters and getters from Blog.class and calling adapter class from main activity like below!! Code for calling adapter class from main activity
mdatabaseReference =
FirebaseDatabase.getInstance().getReference().child("Blog");
userdatabaseReference=
FirebaseDatabase.getInstance().getReference().child("Users");
likesdatabaseReference= FirebaseDatabase.getInstance().getReference().child("Likes");
mDBRefSetup = FirebaseDatabase.getInstance().getReference().child("Users");
mquery = mdatabaseReference.orderByChild("time");
mdatabaseReference.keepSynced(true);
userdatabaseReference.keepSynced(true);
firebaseAuth.addAuthStateListener(authStateListener);
mProgressbar.setMessage("Fetching .....");
mProgressbar.show();
mProgressbar.dismiss();
list = new ArrayList<>();
adapter = new MyCustomAdapter(this,list,firebaseAuth,mdatabaseReference,likesdatabaseReference);
recyclerView = (RecyclerView) findViewById(R.id.blog_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
mchildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mProgressbar.dismiss();
String j = dataSnapshot.getKey();
Log.v("GETKEYZZZ", j);
Blog friendlyMessage = dataSnapshot.getValue(Blog.class);
friendlyMessage.setPostkey(j);
list.add(friendlyMessage);
adapter.notifyDataSetChanged();
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot){}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mquery.addChildEventListener(mchildEventListener);
This is my Adapter class, displaying username,time,description and images using image urls arryalist but its showing one image.
public class MyCustomAdapter extends RecyclerView.Adapter {
Context context;
ArrayList<Blog> list;
List <String> imageUrls;
LayoutInflater inflator;
int lastPosition = 1;
boolean mprogressLike = true,mprogressview = true;
DatabaseReference likeDatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference blogDatabaseReference;
public MyCustomAdapter(Context context, ArrayList<Blog> list,FirebaseAuth firebaseAuth,DatabaseReference blogDatabaseReference, DatabaseReference likeDatabaseReference) {
this.context=context;
this.list=list;
inflator=LayoutInflater.from(context);
this.likeDatabaseReference=likeDatabaseReference;
this.firebaseAuth=firebaseAuth;
this.blogDatabaseReference=blogDatabaseReference;
}
#Override
public myviewholder onCreateViewHolder(ViewGroup parent, int position) {
View v=inflator.inflate(R.layout.posts,parent,false);
myviewholder holder=new myviewholder(v);
return holder;
}
#Override
public void onBindViewHolder(final myviewholder holder, int position) {
final Blog p=list.get(position);
holder.title.setText(p.getTitle());
holder.username.setText(p.getUsername());
holder.viewno.setText(p.getTimestamp());
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
}
for(int i=0; i<imageUrls.size(); i++)
{
Picasso.with(context).load(imageUrls.get(i)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(i));
}
Picasso.with(context).load(p.getImage()).into(holder.userdp);
final String post_key = p.getUid().toString();
Log.v("POST", post_key);
final String current_user= firebaseAuth.getCurrentUser().getUid();
Log.v("CURRENT", current_user);
if(post_key.equals(current_user)){
holder.over.setVisibility(View.VISIBLE);
}else{
holder.over.setVisibility(View.INVISIBLE);
}
#Override
public int getItemCount() {
return list.size();
}
public class myviewholder extends RecyclerView.ViewHolder
{
TextView title,desc,username,likeno,viewno;
ImageView imageview,userdp, over, comments, likes;
ImageButton likebtn,viewbtn;
public myviewholder(View itemView)
{
super(itemView);
title = (TextView) itemView.findViewById(R.id.blog_desc);
username = (TextView) itemView.findViewById(R.id.blog_user_name);
viewno = (TextView) itemView.findViewById(R.id.blog_date);
likeno = (TextView) itemView.findViewById(R.id.blog_like_count);
userdp = (ImageView) itemView.findViewById(R.id.blog_user_image);
imageview = (ImageView) itemView.findViewById(R.id.blog_image);
comments = (ImageView) itemView.findViewById(R.id.blog_comment_icon);
}
popup.show();
}
}
public void filterList(ArrayList<Blog> newList)
{
list=newList;
notifyDataSetChanged();
}
}
finally this is my blog.class:
public class Blog {
String title;
String description;
ArrayList<String> url;
String uid;
int time;
String username;
String image;
String postkey;
String timestamp;
int views;
public int getViews()
{
return views;
}
public void setViews(int views)
{
this.views = views;
}
public String getTimestamp()
{
return timestamp;
}
public void setTimestamp(String timestamp)
{
this.timestamp = timestamp;
}
public int getTime()
{
return time;
}
public void setTime(int time)
{
this.time = time;
}
public String getTitle()
{
return title;
}
public String getUid()
{
return uid;
}
public String getPostkey()
{
return postkey;
}
public void setPostkey(String postkey)
{
this.postkey = postkey;
}
public String getImage()
{
return image;
}
public void setImage(String image)
{
this.image = image;
}
public void setUid(String uid)
{
this.uid = uid;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public void setTitle(String title)
{
this.title = title;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public ArrayList<String> getUrl()
{
return url;
}
public void setUrl(ArrayList<String> url)
{
this.url = url;
}
}
I hope this will work for you.
Use below code.
Picasso.with(context).load(list.get(position).getUrl()).into(holder.imageview);
Log.e("IMGGPOS", list.get(i).getUrl());
Insted of this
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
}
for(int i=0; i<imageUrls.size(); i++)
{
Picasso.with(context).load(imageUrls.get(i)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(i));
}