Show data from Firebase in RecyclerView on Android - java

I currently have implemented RecyclerView, but my CarView does not show the data.
These are my current data in Firebase:
But the RecyclerView shows all three CardViews, but without the records:
These are the files I'm using:
DomiciliarySearchFragment.java
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.didierzuniga.domix.R;
import com.didierzuniga.domix.adapter.OrderAdapterRecyclerView;
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.HashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* A simple {#link Fragment} subclass.
*/
public class DomiciliarySearchFragment extends Fragment {
#Bind(R.id.recycler_order) RecyclerView recyclerView;
public DomiciliarySearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_domiciliary_search, container, false);
showToolbar(getResources().getString(R.string.tab_search), true, view);
ButterKnife.bind(this, view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
new GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("order");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, String> values = (HashMap<String, String>) dataSnapshot.getValue();
recyclerView.setAdapter(new OrderAdapterRecyclerView(values));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});
return view;
}
private class GetDataFromFirebase extends AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
public void showToolbar(String tittle, boolean upButton, View view){
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(tittle);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
}
}
OrderAdapterRecyclerView.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.didierzuniga.domix.R;
import java.util.HashMap;
import java.util.Map;
public class OrderAdapterRecyclerView extends RecyclerView.Adapter<OrderAdapterRecyclerView.ViewHolder>{
private HashMap<String, String> values;
public OrderAdapterRecyclerView(HashMap<String, String> values) {
this.values = values;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_order,parent,false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.fromm.setText(values.get(position));
holder.too.setText(values.get(position));
holder.moneyToPayy.setText(values.get(position));
}
#Override
public int getItemCount() {
return values.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView fromm;
private TextView too;
private TextView moneyToPayy;
ViewHolder(View itemView) {
super(itemView);
fromm = (TextView) itemView.findViewById(R.id.from);
too = (TextView) itemView.findViewById(R.id.to);
moneyToPayy = (TextView) itemView.findViewById(R.id.moneyToPay);
}
}
}
Model: Order.java
public class Order {
public String uid;
public String oFrom;
public String oTo;
public String oHeader;
public String oDescription;
public String oMoneyToPay;
public String oAuthor;
public boolean completed;
public Order(){
}
public Order(String oFrom, String oTo, String oHeader, String oDescription, String oMoneyToPay, String oAuthor) {
this.oFrom = oFrom;
this.oTo = oTo;
this.oHeader = oHeader;
this.oDescription = oDescription;
this.oMoneyToPay = oMoneyToPay;
this.oAuthor = oAuthor;
this.completed = false;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getoFrom() {
return oFrom;
}
public void setoFrom(String oFrom) {
this.oFrom = oFrom;
}
public String getoTo() {
return oTo;
}
public void setoTo(String oTo) {
this.oTo = oTo;
}
public String getoHeader() {
return oHeader;
}
public void setoHeader(String oHeader) {
this.oHeader = oHeader;
}
public String getoDescription() {
return oDescription;
}
public void setoDescription(String oDescription) {
this.oDescription = oDescription;
}
public String getoMoneyToPay() {
return oMoneyToPay;
}
public void setoMoneyToPay(String oMoneyToPay) {
this.oMoneyToPay = oMoneyToPay;
}
public String getoAuthor() {
return oAuthor;
}
public void setoAuthor(String oAuthor) {
this.oAuthor = oAuthor;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
¿What I need to do to be able to display the registers in each CardView?
Thank you!

In DomiciliarySearchFragment.java /onDataChange,
Can you confirm that hashmap has been correctly populated?
I had a similar problem, but the reason was that the data was not stored correctly in the collection

Thanks uguboz, I should have use dataSnapshot.getChildren(), and get all the records one by one in a loop
rv = (RecyclerView) view.findViewById(R.id.recycler_order);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
orders = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new OrderAdapter(orders);
rv.setAdapter(adapter);
database.getReference().child("order").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
orders.removeAll(orders);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Order order = snapshot.getValue(Order.class);
orders.add(order);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you everyone.

Related

Firebase data not displaying in Recycler view. How do I display user specific data from firebase in recyclerview?

I have attached the firebase data image at the bottom for reference. I have a list of users. In that few users have a node called Cart. I need to display the data in the cart for that specific user.
Below is my Activity code
package com.shopping.grocery_ekart.Activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
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 com.shopping.grocery_ekart.Adapters.AdapterOrderUser;
import com.shopping.grocery_ekart.Adapters.AdapterProductUser;
import com.shopping.grocery_ekart.Adapters.CartAdapter;
import com.shopping.grocery_ekart.Models.CartModel;
import com.shopping.grocery_ekart.Models.ModelOrderUser;
import com.shopping.grocery_ekart.Models.ModelProduct;
import com.shopping.grocery_ekart.R;
import java.util.ArrayList;
public class CartActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private RecyclerView recycler_cart;
private ArrayList<CartModel> cartList;
private CartAdapter cartAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
firebaseAuth = FirebaseAuth.getInstance();
recycler_cart = findViewById(R.id.recycler_cart);
loadCartItems();
}
private void loadCartItems() {
//init list
//get orders
cartList = new ArrayList<>();
String timestamp = ""+System.currentTimeMillis();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child("Cart");
reference.orderByChild("uid").equalTo(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//clear list before adding item
cartList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CartModel cartModel = ds.getValue(CartModel.class);
cartList.add(cartModel);
}
//setup adapter
cartAdapter = new CartAdapter(CartActivity.this, cartList);
//set adapter
recycler_cart.setAdapter(cartAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Here is my adapter class
package com.shopping.grocery_ekart.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.shopping.grocery_ekart.Models.CartModel;
import com.shopping.grocery_ekart.Models.ModelProduct;
import com.shopping.grocery_ekart.R;
import java.util.ArrayList;
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.HolderCart> {
private Context context;
public ArrayList<CartModel> cartList;
private FirebaseAuth firebaseAuth;
public CartAdapter(Context context, ArrayList<CartModel> cartList) {
this.context = context;
this.cartList = cartList;
firebaseAuth = FirebaseAuth.getInstance();
}
#NonNull
#Override
public HolderCart onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_itmes, parent, false);
return new HolderCart(view);
}
#Override
public void onBindViewHolder(#NonNull HolderCart holder, int position) {
//get data
CartModel cartModel = cartList.get(position);
String addedBy = cartModel.getAddedBy();
String itemId = cartModel.getItem_Id();
String productId = cartModel.getItem_PID();
String title = cartModel.getItem_Name();
String priceEach = cartModel.getItem_Price_Each();
String price = cartModel.getItem_Price();
String quantity = cartModel.getItem_Quantity();
String availableStock = cartModel.getAvailable_Stock();
//set data
holder.txtName.setText(title);
holder.txtQuantity.setText(quantity);
holder.txtPrice.setText("₹" + price);
holder.priceEach.setText("₹" + priceEach);
holder.availability.setText(availableStock);
}
#Override
public int getItemCount() {
return cartList.size();
}
class HolderCart extends RecyclerView.ViewHolder {
private TextView txtName, txtQuantity, txtPrice, priceEach, availability;
private ImageView imageView, btnMinus, btnPlus, btnDelete;
public HolderCart(#NonNull View itemView) {
super(itemView);
//init ui views
txtName = itemView.findViewById(R.id.txtName);
txtQuantity = itemView.findViewById(R.id.txtQuantity);
txtPrice = itemView.findViewById(R.id.txtPrice);
priceEach = itemView.findViewById(R.id.priceEach);
imageView = itemView.findViewById(R.id.imageView);
btnMinus = itemView.findViewById(R.id.btnMinus);
btnPlus = itemView.findViewById(R.id.btnPlus);
btnDelete = itemView.findViewById(R.id.btnDelete);
availability = itemView.findViewById(R.id.availability);
}
}
}
Here is my Model class
package com.shopping.grocery_ekart.Models;
public class CartModel {
private String AddedBy, Item_Id, Item_PID, Item_Name, Item_Price_Each, Item_Price, Item_Quantity, Available_Stock;
public CartModel() {
}
public CartModel(String addedBy, String itemId, String productId, String title, String priceEach,
String price, String quantity, String availableStock) {
AddedBy = addedBy;
Item_Id = itemId;
Item_PID = productId;
Item_Name = title;
Item_Price_Each = priceEach;
Item_Price = price;
Item_Quantity = quantity;
Available_Stock = availableStock;
}
public String getAddedBy() {
return AddedBy;
}
public void setAddedBy(String addedBy) {
AddedBy = addedBy;
}
public String getItem_Id() {
return Item_Id;
}
public void setItem_Id(String item_Id) {
Item_Id = item_Id;
}
public String getItem_PID() {
return Item_PID;
}
public void setItem_PID(String item_PID) {
Item_PID = item_PID;
}
public String getItem_Name() {
return Item_Name;
}
public void setItem_Name(String item_Name) {
Item_Name = item_Name;
}
public String getItem_Price_Each() {
return Item_Price_Each;
}
public void setItem_Price_Each(String item_Price_Each) {
Item_Price_Each = item_Price_Each;
}
public String getItem_Price() {
return Item_Price;
}
public void setItem_Price(String item_Price) {
Item_Price = item_Price;
}
public String getItem_Quantity() {
return Item_Quantity;
}
public void setItem_Quantity(String item_Quantity) {
Item_Quantity = item_Quantity;
}
public String getAvailable_Stock() {
return Available_Stock;
}
public void setAvailable_Stock(String available_Stock) {
Available_Stock = available_Stock;
}
}
I have a list of users. In that few users have a node called Cart. I need to display the data in the cart for that specific user.
Add this code on CartActivity
recycler_cart.setLayoutManager(new LinearLayoutManager(getActivity()));
onCreate

Couldnt display data from firebase in recyclerview

I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.
But the values are not getting retrieved. It displays a blank activity. I have attached the code.
Applications.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Applications extends AppCompatActivity {
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
RecyclerView recyclerView;
FirebaseUser user;
FirebaseAuth mAuth;
ArrayList<Post> posts;
MyAdap adap;
ProgressDialog pd;
long maxid=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_applications);
recyclerView = findViewById(R.id.work);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
posts = new ArrayList<>();
pd= new ProgressDialog(Applications.this);
pd.setMessage("Loading...");
pd.show();
getSupportActionBar().setTitle("Your Applications");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Job Applications");
Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Post p = ds.getValue(Post.class);
posts.add(p);
}
pd.dismiss();
adap = new MyAdap(Applications.this, posts);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
}
}
Posts.java
public class Post {
private String jobtitle, jobtype, company, location;
public Post() {
}
public Post(String jobtitle, String jobtype, String company, String location) {
this.jobtitle = jobtitle;
this.jobtype = jobtype;
this.company = company;
this.location = location;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
MyAdap.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {
Context cb;
ArrayList<Post> posts;
public MyAdap(Context c, ArrayList<Post> applications){
cb=c;
posts=applications;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.jobTitle.setText(posts.get(position).getJobtitle());
holder.jobType.setText(posts.get(position).getJobtype());
holder.location.setText(posts.get(position).getLocation());
holder.companyName.setText(posts.get(position).getCompany());
}
#Override
public int getItemCount() {
return posts.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView jobTitle, jobType,companyName,location;
public ViewHolder(#NonNull View itemView) {
super(itemView);
jobTitle = itemView.findViewById(R.id.jobTitle);
jobType = itemView.findViewById(R.id.jobType);
companyName = itemView.findViewById(R.id.companyName);
location = itemView.findViewById(R.id.location);
}
}
}
Here is the image of the database.
I think you have a problem with your orderByChild and equalTo method in the Query section. Please try without the Query and if you want to add sorting read details here.
And one more thing you don't have any jobtype in your database but in your POJO class you have this field in your Constructor.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Post p = ds.getValue(Post.class);
posts.add(p);
}
pd.dismiss();
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
You are not attaching adapter to recycle view
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap)
you need to set adpater to recycle view
As said by abdul add the adapter to the recycler view and also add the android lifecycle method onStart(); method and in the add adapter.startlisteneing();

Getting a problem in sending and adding recycler-view data in an activity

I was trying to develop a music app ,so I have two activities like ArtistActivity and FavoriteActivity. My ArtistActivity contains a RecyclerView which loads SongName, SongUrl, SongArtist in a ListView and it loads data from Firebase, and for each item there is a heart bang icon in the end of the item. My main question is when I click item, then I want to send clicked item in other activity which was my FavoriteActivity and I want to play the song when item is clicked on FavoriteActivity. So for this I need to manage SongUrl in FavoriteActivity and I am confused on this topic.
For example :
When we click Add to favorite in some apps and you can take example of Spotify in my app. I want to build same function and i provided my code below. So please if you have any answer regarding my question please answer me.
Here is my code :
My Adapter Class :
package com.geetmp3.GeetMp3.ArtistPanel;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.geetmp3.GeetMp3.R;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import xyz.hanks.library.bang.SmallBangView;
public class PanelAdapter extends RecyclerView.Adapter<PanelAdapter.PanelViewHolder> {
private Context mContext;
private List<PanelList> mUploads;
public PanelAdapter(Context context, List<PanelList> panelList) {
mContext = context;
mUploads = panelList;
}
#NonNull
#Override
public PanelViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.artist_recycler_layout, parent, false);
return new PanelViewHolder(v);
// Toast.makeText(mContext, "" + ge, Toast.LENGTH_SHORT).show();
}
#Override
public void onBindViewHolder(#NonNull PanelViewHolder holder, int position) {
PanelList panelList = mUploads.get(position);
holder.textViewName.setText(panelList.getSongName());
Glide.with(mContext)
.load(panelList.getSongImageUri())
.centerCrop()
.into(holder.circleImageView);
//
holder.bangView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.bangView.isSelected()) {
holder.bangView.setSelected(false);
// What can i do here
} else {
holder.bangView.setSelected(true);
holder.bangView.likeAnimation(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Toast.makeText(mContext, mUploads.get(position).getSongName() + "Added to playlist", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class PanelViewHolder extends RecyclerView.ViewHolder {
private TextView textViewName;
private CircleImageView circleImageView;
private LinearLayout thisLayout;
private SmallBangView bangView;
public PanelViewHolder(#NonNull View itemView) {
super(itemView);
thisLayout = itemView.findViewById(R.id.artist_linear);
textViewName = itemView.findViewById(R.id.artist_song_name);
circleImageView = itemView.findViewById(R.id.artist_songs_image);
bangView = itemView.findViewById(R.id.bang_like_heart);
}
}
}
My getter and setter class:
public class PanelList {
private String SongName;
private String SongUrl;
private String SongImageUri;
private String SongLyrics;
private String SongMusicDirector;
private String SongProducer;
private String SongArtist;
public PanelList() {
}
public PanelList(String SongName, String SongUrl, String SongImageUri, String SongArtist, String SongLyrics, String SongMusicDirector, String SongProducer) {
this.SongName = SongName;
this.SongUrl = SongUrl;
this.SongImageUri = SongImageUri;
this.SongArtist = SongArtist;
this.SongLyrics = SongLyrics;
this.SongMusicDirector = SongMusicDirector;
this.SongProducer = SongProducer;
}
public String getSongArtist() {
return SongArtist;
}
public String getSongLyrics() {
return SongLyrics;
}
public String getSongMusicDirector() {
return SongMusicDirector;
}
public String getSongProducer() {
return SongProducer;
}
public String getSongName() {
return SongName;
}
public String getSongUrl() {
return SongUrl;
}
public String getSongImageUri() {
return SongImageUri;
}
}
My artist Activity :
public class ArtistActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ValueEventListener eventListener;
private DatabaseReference mDataRef, artist_ref;
private List<PanelList> mList;
private PanelAdapter panelAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.artist1layout);
mRecyclerView = findViewById(R.id.artist_song_recyclerview);
mDataRef = FirebaseDatabase.getInstance().getReference("ArtistView").child(getIntent().getStringExtra("Artist"))
.child("Songs");
mRecyclerView.setHasFixedSize(true);
mDataRef.keepSynced(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mList = new ArrayList<>();
panelAdapter = new PanelAdapter(ArtistActivity.this, mList);
mRecyclerView.setAdapter(panelAdapter);
eventListener = mDataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PanelList list = postSnapshot.getValue(PanelList.class);
mList.add(list);
}
panelAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
There is nothing in my FavoriteActivity except onCreate.
Don't pass the list in adapter if it is dynamic.
Add this function in your adapter
public void setPanelList(List<PanelList> panelList){
panelList = mList;
notifyDataSetChanged();
}
Modify your mDataRef.addValueEventListener
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PanelList list = postSnapshot.getValue(PanelList.class);
mList.add(list);
}
panelAdapter.setPanelList(mList);
}
Hope this helps.

Can't retrieve data array item from model in Firebase Recycler Adapter android java

I have problem to retrieve data which one of item has type arrayList into recyclerView. Previously, I've asked and discussed about the right model for url_photo_collage on How to retrieve array data from children node in Firebase Realtime Database Java? (Firebase Recycler Adapter) but the problem is my recyclerview has showed nothing .
This is my structure database was described in this Picture
There are classes I 've tried which followed with the suggestion before
In the model class, I've changed the data type of url_photo_collegeto be List
DolanItemClass.Java
package co.id.roningrum.firebasearrayimage;
import java.util.List;
public class DolanItemClass {
private String name_tourism;
private String location_tourism;
private String info_tourism;
private String telepon;
private String url_photo;
private List<String> url_photo_collage;
private double lat_location_tourism;
private double lng_location_tourism;
public DolanItemClass() {
//constructor untuk panggilan ke DataSnapshot.getValue
}
public DolanItemClass(String name_tourism, String location_tourism, String info_tourism, String telepon, String url_photo, List<String> url_photo_collage, double lat_location_tourism, double lng_location_tourism) {
this.name_tourism = name_tourism;
this.location_tourism = location_tourism;
this.info_tourism = info_tourism;
this.telepon = telepon;
this.url_photo = url_photo;
this.url_photo_collage = url_photo_collage;
this.lat_location_tourism = lat_location_tourism;
this.lng_location_tourism = lng_location_tourism;
}
public List<String> getUrl_photo_collage() {
return url_photo_collage;
}
public String getName_tourism() {
return name_tourism;
}
public void setName_tourism(String name_tourism) {
this.name_tourism = name_tourism;
}
public String getLocation_tourism() {
return location_tourism;
}
public void setLocation_tourism(String location_tourism) {
this.location_tourism = location_tourism;
}
public String getInfo_tourism() {
return info_tourism;
}
public void setInfo_tourism(String info_tourism) {
this.info_tourism = info_tourism;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
public String getUrl_photo() {
return url_photo;
}
public void setUrl_photo(String url_photo) {
this.url_photo = url_photo;
}
public double getLat_location_tourism() {
return lat_location_tourism;
}
public void setLat_location_tourism(double lat_location_tourism) {
this.lat_location_tourism = lat_location_tourism;
}
public double getLng_location_tourism() {
return lng_location_tourism;
}
public void setLng_location_tourism(double lng_location_tourism) {
this.lng_location_tourism = lng_location_tourism;
}
}
because of showing recyclerview on DetailActivity, I created the new class viewholder especially for url_photo_college item
DolanImageViewHolder.class
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class DolanImageViewHolder extends RecyclerView.ViewHolder {
private final ImageView imgDetailData;
private List<String> urlPhotoArray;
public DolanImageViewHolder(#NonNull View itemView) {
super(itemView);
imgDetailData = itemView.findViewById(R.id.img_detail_item_data);
}
public void showImageArray(DolanItemClass dolanItemClass){
urlPhotoArray = dolanItemClass.getUrl_photo_collage();
Glide.with(itemView.getContext()).load(urlPhotoArray).into(imgDetailData);
Log.d("Pesan", "List"+urlPhotoArray);
}
}
And the url_photo_college item will show in Detail Activity. But unfortunately rectclerview show nothing. It show through method show data
DetailTouristActivity.class
package co.id.roningrum.firebasearrayimage;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
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.Query;
import com.google.firebase.database.ValueEventListener;
public class DetailTouristListAct extends AppCompatActivity {
private ImageView imgDetailData;
private TextView tvNamaDetail, tvAlamatDetail, tvDescDetail;
private RecyclerView rvImageDetailCollages;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListener;
private FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder> firebaseRecyclerAdapter;
public static final String EXTRA_WISATA_KEY = "tourist_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_tourist_list);
String touristKey = getIntent().getStringExtra(EXTRA_WISATA_KEY);
if(touristKey == null){
throw new IllegalArgumentException("Must pass Extra");
}
imgDetailData = findViewById(R.id.img_detail_data);
tvNamaDetail = findViewById(R.id.tv_name_detail);
tvAlamatDetail = findViewById(R.id.tv_info_tourism_detail);
tvDescDetail = findViewById(R.id.tv_address_detail);
rvImageDetailCollages = findViewById(R.id.rv_photo_collage);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Tourism").child(touristKey);
rvImageDetailCollages.setLayoutManager(new GridLayoutManager(this, 2));
LoadDetailData();
}
private void ShowCollage() {
Query query = databaseReference.child("url_photo_collage");
FirebaseRecyclerOptions<DolanItemClass> options = new FirebaseRecyclerOptions.Builder<DolanItemClass>()
.setQuery(query, DolanItemClass.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull DolanImageViewHolder dolanImageViewHolder, int i, #NonNull DolanItemClass dolanItemClass) {
dolanImageViewHolder.showImageArray(dolanItemClass);
}
#NonNull
#Override
public DolanImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DolanImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_data, parent, false));
}
};
firebaseRecyclerAdapter.notifyDataSetChanged();
rvImageDetailCollages.setAdapter(firebaseRecyclerAdapter);
}
private void LoadDetailData() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DolanItemClass dolanItemClass = dataSnapshot.getValue(DolanItemClass.class);
tvNamaDetail.setText(dolanItemClass.getName_tourism());
tvAlamatDetail.setText(dolanItemClass.getLocation_tourism());
tvDescDetail.setText(dolanItemClass.getInfo_tourism());
Glide.with(getApplicationContext()).load(dolanItemClass.getUrl_photo()).into(imgDetailData);
ShowCollage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
}
#Override
protected void onStart() {
super.onStart();
LoadDetailData();
if(firebaseRecyclerAdapter!=null){
firebaseRecyclerAdapter.startListening();
}
}
#Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListener);
}
}
The output goal is recyclerview can show data eventhought the item data type is List
Here's the error
urlPhotoArray = dolanItemClass.getUrl_photo_collage();
You have to call the index from the List by adding .get(0) if you want the first element.
Your code should be
urlPhotoArray = dolanItemClass.getUrl_photo_collage().get(0);

How to structure data in firebase database as a List<String>?

I would like to know how to structure my data in Firebase database so it return a List<String> when queried. I'm implementing a image slider, I need Firebase to return a List containing images url that my model class which implement Parcelable can parse.
Here is my model class
public class Property implements Parcelable {
private int price;
private String address;
private int numberOfBed;
private int numberOfBath;
private int numberOfCar;
private List<String> propertyImage= new ArrayList<>();
private float lotDim;
public Property() { } //Needed for Firebase's auto data mapping
public Property(int price, String address, int numberOfBed, int numberOfBath,
int numberOfCar, List<String> propertyImage, float lotDim) {
this.price = price;
this.address = address;
this.numberOfBed = numberOfBed;
this.numberOfBath = numberOfBath;
this.numberOfCar = numberOfCar;
this.propertyImage = propertyImage;
this.lotDim = lotDim;
}
protected Property(Parcel in) {
price = in.readInt();
address = in.readString();
numberOfBed=in.readInt();
numberOfBath = in.readInt();
numberOfCar = in.readInt();
in.readStringList(propertyImage);
lotDim = in.readFloat();
}
public static final Creator<Property> CREATOR = new Creator<Property>() {
#Override
public Property createFromParcel(Parcel in) {
return new Property(in);
}
#Override
public Property[] newArray(int i) {
return new Property[i];
}
};
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumberOfBed() {
return numberOfBed;
}
public void setNumberOfBed(int numberOfBed) {
this.numberOfBed = numberOfBed;
}
public int getNumberOfBath() {
return numberOfBath;
}
public void setNumberOfBath(int numberOfBath) {
this.numberOfBath = numberOfBath;
}
public int getNumberOfCar() {
return numberOfCar;
}
public void setNumberOfCar(int numberOfCar) {
this.numberOfCar = numberOfCar;
}
public List<String> getPropertyImage() {
return propertyImage;
}
public void setPropertyImage(List<String> propertyImage) {
this.propertyImage = propertyImage;
}
public float getLotDim() {
return lotDim;
}
public void setLotDim(float lotDim) {
this.lotDim = lotDim;
}
#Override
public int describeContents(){
return 0;
}
#Override
public void writeToParcel( Parcel dest, int flags){
dest.writeInt(price);
dest.writeString(address);
dest.writeInt(numberOfBed);
dest.writeInt(numberOfBath);
dest.writeInt(numberOfCar);
dest.writeStringList(propertyImage);
dest.writeFloat(lotDim);
}
}
Here is my current Firebase structure. it return a String actually. I want it to return a List of propertyImage.
This is the fragment that will use the model class, That's where I need to implement the code. Notice at the bottom, I work out something, in the firebase database I appended all the urls in one string(well it's a dirty solution), and split the url turning that String into an array. :-)
So how to implement the new code provided by #Alex Mano. thanks guys
package com.realty.drake.kunuk;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Created by drake on 4/11/18
*/
public class Tab1Buy extends Fragment {
private DatabaseReference propertyRef;
private RecyclerView mPropertyRecyclerView;
FirebaseRecyclerAdapter<Property, PropertyViewHolder> mPropertyAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.property_tab, container, false);
mPropertyRecyclerView = rootView.findViewById(R.id.property_recyclerView);
return rootView;
}
//TODO Check internet and display error msg if internet down
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPropertyRecyclerView.hasFixedSize();
mPropertyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final ProgressBar progressBar = view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
propertyRef = FirebaseDatabase.getInstance()
.getReference()
.child("Buy");
propertyRef.keepSynced(true);
// keyQuery - the Firebase location containing the list of keys to be found in dataRef
//Query personQuery = personRef.orderByKey();
FirebaseRecyclerOptions<Property> options =
new FirebaseRecyclerOptions.Builder<Property>()
.setQuery(propertyRef, Property.class)
.build();
mPropertyAdapter = new FirebaseRecyclerAdapter<Property, PropertyViewHolder>(options) {
#Override
// Bind the Property object to the ViewHolder PropertyHolder
public void onBindViewHolder(#NonNull PropertyViewHolder holder,
final int position, #NonNull final Property model) {
holder.setPrice(model.getPrice());
holder.setAddress(model.getAddress());
holder.setNumberOfBed(model.getNumberOfBed());
holder.setNumberOfBath(model.getNumberOfBath());
holder.setNumberOfCar(model.getNumberOfCar());
holder.setPropertyImage(model.getPropertyImage());
//Intent send Parcelable to PropertyDetail
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().startActivity(new Intent(getActivity(), PropertyDetail.class)
.putExtra("Property", model));
}
});
}
#Override
public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.property_card for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.property_card, parent, false);
return new PropertyViewHolder(view);
}
#Override
public void onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
progressBar.setVisibility(View.GONE);
}
//TODO Implement onError
#Override
public void onError(#NonNull DatabaseError e) {
// Called when there is an error getting data. You may want to update
// your UI to display an error message to the user.
// ...
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "DatabaseError", Toast.LENGTH_SHORT).show();
}
};
mPropertyRecyclerView.setAdapter(mPropertyAdapter);
}
#Override
public void onStart() {
super.onStart();
mPropertyAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mPropertyAdapter.stopListening();
}
public class PropertyViewHolder extends RecyclerView.ViewHolder {
View mView;
public PropertyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPrice(int price) {
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView Price = mView.findViewById(R.id.post_price);
Price.setText(currencyPrice);
}
public void setAddress(String address){
TextView Address = mView.findViewById(R.id.post_address);
Address.setText(String.valueOf(address));
}
public void setNumberOfBed(int numberOfBed){
TextView NumberOfBed = mView.findViewById(R.id.post_bedroom);
NumberOfBed.setText(String.valueOf(numberOfBed));
}
public void setNumberOfBath(int numberOfBath){
TextView NumberOfBath = mView.findViewById(R.id.post_bathroom);
NumberOfBath.setText(String.valueOf(numberOfBath));
}
public void setNumberOfCar(int numberOfCar) {
TextView NumberOfCar = mView.findViewById(R.id.post_garage);
NumberOfCar.setText(String.valueOf(numberOfCar));
}
public void setPropertyImage(String propertyImage){
ImageView imageView = mView.findViewById(R.id.post_propertyImage);
//take one long string containing multiple url in and parse it
String propertyImageArray[] = propertyImage.split(",");
//TODO add loading icon for placeholder
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getContext())
.load(propertyImageArray[0])
.fitCenter()
.into(imageView);
}
}
}
Assuming that the Buy node is a direct child of your Firebase root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference propertyImageRef = rootRef.child("Buy").child("1").child("propertyImage");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
propertyImageRef.addListenerForSingleValueEvent(valueEventListener);
The output will be all those urls.

Categories

Resources