How can I get selecting value in FirebaseRecyclerAdapter? - android

I want to obtain determined value from the Realtime DB using FirebaseRecyclerAdapter. This is my class:
public class ProductAvtivity extends AppCompatActivity {
private final String TAG = "ProductActivity";
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private FirebaseDatabase database;
private DatabaseReference mProductReference;
private Query mMachineReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_avtivity);
database = FirebaseDatabase.getInstance();
mProductReference = database.getReference().child("products");
String idmachine = getIntent().getStringExtra("idmachine");
mMachineReference = database.getReference().child("machines").child("_id").equalTo(idmachine);
Log.d(TAG + "idmachine",idmachine);
mRecyclerView = (RecyclerView) findViewById(R.id.product_recyclerview);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
FirebaseRecyclerAdapter<Product,ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Product, ProductViewHolder>(Product.class,R.layout.view_product,ProductViewHolder.class,mProductReference) {
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
viewHolder.productName.setText(model.name);
}
};
mRecyclerView.setAdapter(adapter);
}
public static class ProductViewHolder extends RecyclerView.ViewHolder{
TextView productName;
public ProductViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.product_name);
}
}
}
I tried it with this solution but it's not working because the activity crashes:
public class ProductAvtivity extends AppCompatActivity {
private final String TAG = "ProductActivity";
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private FirebaseDatabase database;
private DatabaseReference mProductReference;
private Query mMachineReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_avtivity);
database = FirebaseDatabase.getInstance();
mProductReference = database.getReference().child("products");
String idmachine = getIntent().getStringExtra("idmachine");
mMachineReference = database.getReference().child("machines").child("_id").equalTo(idmachine);
Log.d(TAG + "idmachine",idmachine);
mRecyclerView = (RecyclerView) findViewById(R.id.product_recyclerview);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
FirebaseRecyclerAdapter<Product,ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Product, ProductViewHolder>(Product.class,R.layout.view_product,ProductViewHolder.class,mProductReference) {
#Override
protected void populateViewHolder(final ProductViewHolder viewHolder, final Product model, int position) {
mMachineReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Machine machine = dataSnapshot.getValue(Machine.class);
for (Integer i : machine.id_prod){
if (model._id == i){
viewHolder.productName.setText(model.name);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mRecyclerView.setAdapter(adapter);
}
public static class ProductViewHolder extends RecyclerView.ViewHolder{
TextView productName;
public ProductViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.product_name);
}
}
}
I have a list of product for all machine IDs and then I pass this from another activity where the user selects the machine. By this selection, I have to list in the recyclerview the product connected to it.

Related

RecycerView always reset back to first position after inserting new Firebase data

My recyclerview always reset to first position after new data is inserted to firebase. In my TestAdapter class, I have an onClickListener which increments like on a post when clicked. Whenever I click on this "like" button, view is reset to first position. I believe this issue is related to setAdapter() being called on data changed. Please help!
MainActivity fetches "post" data from Firebase and populates it in TestAdapter class.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private TestAdapter testAdapter;
private ArrayList<Post> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
fetchPostFromDB();
}
private void fetchPostFromDB() {
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("Post");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postList = new ArrayList<>();
for (DataSnapshot snap : snapshot.getChildren()) {
String post = snap.child("post").getValue().toString();
Post post = new Post(post);
postList.add(post);
}
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
TestAdapter binds the data (postList) and has an onClickListener.
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestHolder> {
private List<Post> postList;
private Context context;
private DatabaseReference databaseReference;
public TestAdapter(Context ct, ArrayList<Post> postList) {
context = ct;
this.postList = postList;
}
#NonNull
#Override
public TestHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.post_item, parent, false);
final TestHolder holder = new TestHolder(view);
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
databaseReference.setValue(incrementLike);
}
});
return holder;
}
#Override
public void onBindViewHolder(#NonNull final TestHolder holder, final int position) {
holder.tvPost.setText(postList.get(position).getPost());
holder.tvVotes.setText(Integer.toString(postList.get(position).getLikes()));
}
#Override
public int getItemCount() {
return postList.size();
}
public static class TestHolder extends RecyclerView.ViewHolder {
TextView tvPost, tvLikes;
ImageButton ibLike;
public TestHolder(#NonNull View itemView) {
super(itemView);
tvPost = itemView.findViewById(R.id.tvPost);
tvLikes = itemView.findViewById(R.id.tvLikes);
ibLike = itemView.findViewById(R.id.ibLike);
}
}
Here need to initialize your adapter class from main activity. and then when data received just call adapter.notifiyDatasetChanged like:
onCreate():
postList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
and from your fetchPostFromDB delete adapter initialization insted of this just put this line testAdapter.notifiyDataSetChanged()
And when click on text button you can update/handle like this:
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
postList.get(holder.getAdapterPosition()).setLikes(incrementLike);
databaseReference.setValue(incrementLike);
notifyDataSetChanged();
}
});

Retrieving data from firebase to recyclerview does not work

As mentioned in the title, my recyclerview does not work. No idea why, because I do not get any errors or anything in the logcat or while building the app. Is there a way I could debug this or could you point out the mistake that I did?
I've implemented another recyclerview with the adapter, but I used a simple adapter. I tried using the firebaseUI in this case, and it seems that the adapter somehow cannot retrieve the data from the firebase firestore.
https://imgur.com/a/JSLXuou The screenshot of my database structure.
My adapter:
public class ManageAdapter extends FirestoreRecyclerAdapter<Manage, ManageAdapter.ManageHolder> {
public ManageAdapter(#NonNull FirestoreRecyclerOptions<Manage> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ManageHolder holder, int position, #NonNull Manage model) {
holder.textviewName.setText(model.getName());
holder.textviewGrade.setText(model.getGrade());
//holder.textviewAge.setText(String.valueOf(model.getAge()));
}
#NonNull
#Override
public ManageHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.manage_item,
parent,false);
return new ManageHolder(v);
}
class ManageHolder extends RecyclerView.ViewHolder{
TextView textviewName;
TextView textviewAge;
TextView textviewGrade;
public ManageHolder(#NonNull View itemView) {
super(itemView);
textviewAge = itemView.findViewById(R.id.manage_item_title_age);
textviewGrade = itemView.findViewById(R.id.manage_item_grade);
textviewName = itemView.findViewById(R.id.manage_item_name);
}
}
}
Main class:
private FirebaseFirestore firebaseFirestore;
private Toolbar mToolbar;
private Button delete_event;
private RecyclerView participants;
private TextView manage_events_title;
private TextView participans_text;
private ManageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_events);
final String ID = getIntent().getExtras().getString("ID");
firebaseFirestore = FirebaseFirestore.getInstance();
delete_event = (Button) findViewById(R.id.delete_event);
manage_events_title = (TextView) findViewById(R.id.manage_events_title);
participans_text = (TextView) findViewById(R.id.participants_text);
participants = (RecyclerView) findViewById(R.id.recyclerview_manage);
setUpRecyclerView();
}
private void setUpRecyclerView(){
final String ID = getIntent().getExtras().getString("ID");
Query query = firebaseFirestore.collection("Events").document(ID).collection("Users");
FirestoreRecyclerOptions<Manage> options = new FirestoreRecyclerOptions.Builder<Manage>()
.setQuery(query, Manage.class).build();
adapter = new ManageAdapter(options);
participants.setHasFixedSize(true);
participants.setLayoutManager(new LinearLayoutManager(this));
participants.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}

When/How to declare recyclerView adapter while waiting for database to be fetched from Firebase

I'll appreciate if anyone can help me with this.
So what's happening is the Adapter is being declared before the SenderNames Array List is fetched from Firebase Database.So how do I wait for the SenderNames to be fetched first from database and then display them?
Tab 2 code
public class Tab2 extends Fragment {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<String> reminderMessages;
protected static ArrayList<String> senderNames;
String receiverUID;
private DatabaseReference mDatabase;
int i =0;
private Button profile;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
View v =inflater.inflate(R.layout.tab2, container, false);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
reminderMessages = new ArrayList<>();
receiverUID = user.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("reminders").orderByChild("receiverUID").equalTo(receiverUID);
//Setting size of recycler view as constant
recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view2);
recyclerView.setHasFixedSize(true);
//Setting Linear Layout
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
senderNames = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//Getting corresponding username of the ReceiverUID
//Getting senderUID
String sUID = ds.child("senderUID").getValue(String.class);
//Getting senders Name
GetSenderName getName = new GetSenderName();
getName.GetSenderssName(sUID);
//Getting message from database
String message = ds.child("reminderMessage").getValue(String.class);
//Adding database to ArrayList
reminderMessages.add(message);
//Getting corresponding username of the ReceiverUID
// Log.d("String names", receiverNames.toString());
}
adapter = new DataAdapter(reminderMessages,senderNames);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Error in Reaching Database
Toast.makeText(getContext(), "Something went Wrong!", Toast.LENGTH_SHORT).show();
}
});
return v;
}
GetSenderName Class
import static com.example.admin.import2.Tab2.senderNames;
public class GetSenderName {private FirebaseAuth auth;
ListView listView;
private DatabaseReference mDatabase;
private String senderName;
public void GetSenderssName(String UID){
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
//Running a query to find matching UID
Query query = mDatabase.orderByKey().equalTo(UID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot2) {
// Getting user name with matching UID
for (DataSnapshot users : dataSnapshot2.getChildren()) {
senderName = users.child("username").getValue(String.class);
senderNames.add(senderName);
Log.d("sendername retrieved",senderNames.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
DataAdapter Class
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<String> reminderMessage;
private ArrayList<String> receiverName;
public DataAdapter(ArrayList<String> reminderMessage,ArrayList<String> receiverName) {
this.reminderMessage = reminderMessage;
this.receiverName = receiverName;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup,int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cards_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.reminderText.setText(reminderMessage.get(i));
viewHolder.receiverName.setText(receiverName.get(i));
}
#Override
public int getItemCount() {
return reminderMessage.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView reminderText;
private TextView receiverName;
public ViewHolder(View view) {
super(view);
reminderText = (TextView)view.findViewById(R.id.remindertext);
receiverName = (TextView)view.findViewById(R.id.receiverName);
}
}
}
To avoid problems like populate a list before the databases values are fetched, you should use a FirebaseRecyclerAdapter available in firebaseUI library.
It work in asynchronously so you dont need to do nothing. Just set up the recyclerview, the adapter and the query.
Take a look at the official repository
FirebaseUI
Instead of sending the data in constructor you can create some setter method to set the data and update the list,
Remove the arguments in Adapter constructor
Initialize the ArrayList while declaring as a global variable.
Create a setter method to set the data,
If you do your Adapter will be like this,
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<String> reminderMessage = new ArrayList<>();
private ArrayList<String> receiverName = new ArrayList<>();
public DataAdapter(ArrayList<String> reminderMessage, ArrayList<String> receiverName) {
this.reminderMessage = reminderMessage;
this.receiverName = receiverName;
}
public void setData(ArrayList<String> reminderMessage, ArrayList<String> receiverName) {
if(reminderMessage == null || receiverName != null) {
return;
}
this.reminderMessage.clear();
this.receiverName.clear();
this.reminderMessage.addAll(reminderMessage);
this.receiverName.addAll(receiverName);
notifyDataSetChanged();
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cards_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.reminderText.setText(reminderMessage.get(i));
viewHolder.receiverName.setText(receiverName.get(i));
}
#Override
public int getItemCount() {
return reminderMessage.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView reminderText;
private TextView receiverName;
public ViewHolder(View view) {
super(view);
reminderText = (TextView) view.findViewById(R.id.remindertext);
receiverName = (TextView) view.findViewById(R.id.receiverName);
}
}
}
so from your activity you can call like this, adapter.setData(reminderMessages,senderNames); so that you can create the adapter and set in Recycle View before get the data from server.

Android - Load data from Firebase Database in Fragment

I have a NavigationDrawer activity which is using fragments. In one of my fragments I want to load data from the Firebase database to a RecyclerView.
So I have an ArrayList for the objects I have stored in the database. Then I add a ValueEventListener to my database reference where I add the objects from the database to the array list. And then I give the ArrayList to the RecyclerView Adapter which should create the list with my objects.
When I use addListenerForSingleValueEvent it is never working, I always get an empty RecyclerView. When I use addValueEventListener it is working neither at the start, but when I switch the orientation of my phone to landscape the data suddenly appears. And if I go back to the normal orientation it is still there. But not at the start when I open the fragment.
Here is my code of the fragment class:
public class LogFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter rvAdapter;
private RecyclerView.LayoutManager rvLayoutManager;
private ArrayList<LogEntry> entries;
private DatabaseReference databaseReference;
private DatabaseReference logReference;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
public LogFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_log, container, false);
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
loadEntries();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
rvLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(rvLayoutManager);
rvAdapter = new RvAdapter(entries);
recyclerView.setAdapter(rvAdapter);
// Inflate the layout for this fragment
return rootView;
}
private void loadEntries(){
entries = new ArrayList<>();
logReference = databaseReference.child("log").child(firebaseUser.getUid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
entries.add(ds.getValue(LogEntry.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("LogFragment", "loadLog:onCancelled", databaseError.toException());
}
};
logbuchReference.addValueEventListener(valueEventListener);
}
}
And here is my RvAdapter.java:
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.MyViewHolder> {
private ArrayList<LogEntry> entries;
public RvAdapter(ArrayList<LogEntry> entries){
this.entries = entries;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.log_entry_item, null);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
holder.tvAction.setText(entries.get(position).action);
holder.tvDate.setText(dateFormat.format(entries.get(position).date)+"\n"+timeFormat.format(entries.get(position).date));
holder.ivIcon.setImageResource(entries.get(position).icon);
holder.itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// Do something
}
});
}
#Override
public int getItemCount() {
return entries.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvAction, tvDate;
ImageView ivIcon;
public MyViewHolder(View itemView) {
super(itemView);
tvAction = (TextView) itemView.findViewById(R.id.tvAction);
tvDate = (TextView) itemView.findViewById(R.id.tvDate);
ivIcon = (ImageView) itemView.findViewById(R.id.ivIcon);
}
}
}
And here my LogEntry.java:
public class LogEntry {
public String action;
public Date date;
public int icon;
public String message;
public LogEntry() {}
public LogEntry(String action, Date date, int icon, String message) {
this.action = action;
this.date = date;
this.icon = icon;
this.message = message;
}
}
Someone know what could be the problem?
EDIT:
When I System.out.prinln the ArrayList right after the for() I get the data. So loading the data from the database is working. But presenting the data is not working.
Firebase is asynchronous. Set or notify the adapter from within the callback.
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
entries.add(ds.getValue(LogEntry.class));
}
// Declare adapter and set here
// OR... adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("LogFragment", "loadLog:onCancelled", databaseError.toException());
}
};
In more detail,
loadEntries(); // ... Doing stuff in the background
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
rvLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(rvLayoutManager);
rvAdapter = new RvAdapter(entries); // This is still empty, probably
recyclerView.setAdapter(rvAdapter);
// entries.add() called later, but adapter never notified
You can use https://github.com/firebase/FirebaseUI-Android to solve this problem.
follow a little code to help you...
ListView messagesView = (ListView) findViewById(R.id.messages_list);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
mAdapter = new FirebaseListAdapter<Chat>(this, Chat.class, android.R.layout.two_line_list_item, ref) {
#Override
protected void populateView(View view, Chat chatMessage, int position) {
((TextView)view.findViewById(android.R.id.text1)).setText(chatMessage.getName());
((TextView)view.findViewById(android.R.id.text2)).setText(chatMessage.getText());
}
};
messagesView.setAdapter(mAdapter);
Good luck!!!

Unable to load more than one row using FirebaseRecyclerAdapter

I am trying to fetch the data from firebase, using firebaseRecyclerAdapter. But I am unable to populate all the data from the firebase database to the RecyclerView.
Database is as follows:
The output I am getting is only from the "qqq" row
rvlist Class:
public class rvlist {
String name, propellant;
public rvlist() {
}
public rvlist(String name, String propellant) {
this.name = name;
this.propellant = propellant;
}
public String getName() {
return name;
}
public String getPropellant() {
return propellant;
}
}
MyViewHolder:
public class MyViewHolder extends RecyclerView.ViewHolder {
View mView;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView field = (TextView) mView.findViewById(R.id.a);
field.setText(name);
}
public void setPropellant(String text) {
TextView field = (TextView) mView.findViewById(R.id.b);
field.setText(text);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseReference mRef;
RecyclerView rv;
ProgressBar pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pb = (ProgressBar)findViewById(R.id.pb);
pb.setVisibility(View.VISIBLE);
rv = (RecyclerView) findViewById(R.id.rvv);
rv.setLayoutManager(new LinearLayoutManager(this));
mRef = FirebaseDatabase.getInstance().getReference().child("table");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<rvlist, MyViewHolder> recyclerAdapter = new FirebaseRecyclerAdapter<rvlist, MyViewHolder>
(rvlist.class, R.layout.model, MyViewHolder.class, mRef) {
#Override
public void populateViewHolder(MyViewHolder itemsViewHolder, rvlist items, int position) {
pb.setVisibility(View.GONE);
itemsViewHolder.setName(items.getName());
itemsViewHolder.setPropellant(items.getPropellant());
}
};
rv.setAdapter(recyclerAdapter);
}
}
Make sure your RecyclerView and adapter layout_height is set to wrap_content not to match_parent
<android.support.v7.widget.RecyclerView
android:id="#+id/recv_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="LinearLayoutManager"
...>
</android.support.v7.widget.RecyclerView>

Categories

Resources