I am trying to create a tablayout with 3 fragments. One of them is AllPostFragment. Initially the fragment is set to show - "No new food posts!". After onCreateView, i wish to fetch the posts from the database and update them inside the listview. Here is the code for AllPostFragment.
public class AllPostFragment extends ListFragment{
String Username;
ArrayList<String> posts = new ArrayList<>();
public AllPostFragment(String Username)
{
this.Username=Username;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_all_post_fragment, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference postref=firebaseDatabase.getReference("posts");
postref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot snap : snapshot.getChildren()){
String s="Type: "+snap.child("type").getValue()+"\n"+"Name: "+snap.child("name").getValue()+"\n"+"Phone: "+snap.child("phoneNo").getValue()+"\n"+"City: "+snap.child("city").getValue()+"\n"+"PostedBy: "+snap.child("Username").getValue();
posts.add(s);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ArrayAdapter<String> adapter=new ArrayAdapter<(getListView().getContext(),android.R.layout.simple_list_item_1,posts);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
I am updating the posts onResume but i want to update them before the first view is loaded. But when I try to set the arrayadapter in the onCreateView method, it says view not created.The code for the xml file is als attached below.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".AllPostFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#AEC5EB"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:id="#android:id/list"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#android:id/empty"
android:text="No new food posts!"/>
</RelativeLayout>
Related
I have a SwipeRefreshLayout on my RecyclerView, I want the items to refresh as the user scrolls down instead of just pulling down from the top every time. I need something like Instagram or facebook that the posts load as the user is scrolling down. So that the user doesn't have to keep coming up again and again to refresh and load more posts
Here is my XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bar">
</com.google.android.material.appbar.AppBarLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/bar">
<androidx.core.widget.NestedScrollView
android:id="#+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bar">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bar"
android:id="#+id/recycler_view_posts"/>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
Here is my fragment code:
public class HomeFragment extends Fragment {
//POSTS
private RecyclerView recyclerViewPosts;
private PostAdapter postAdapter;
private List<Post> postLists;
private List<String> followingList;
private Context mContext;
private static final int TOTAL_NUMBER_OF_ITEMS_TO_LOAD = 5;
private SwipeRefreshLayout swipeRefreshLayout;
private int currentPage = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
//POSTS
recyclerViewPosts = view.findViewById(R.id.recycler_view_posts);
recyclerViewPosts.setHasFixedSize(true);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerViewPosts.setLayoutManager(linearLayoutManager);
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists);
recyclerViewPosts.setAdapter(postAdapter);
swipeRefreshLayout = view.findViewById(R.id.swiperefresh);
checkFollowing();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
#Override
public void onRefresh() {
currentPage++;
postLists.clear();
readPosts();
}
});
return view;
}
private void readPosts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
Query postQuery = reference.limitToLast(currentPage * TOTAL_NUMBER_OF_ITEMS_TO_LOAD);
postQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
postLists.add(post);
}
postAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I would recommend you to use the Paging Library from Android. It is design for it and you have a nice tutorial for it here. It might be a bit of work but it is worth it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to fetch data from firebase and put it into a recycler view through adapter. But, no data is being displayed.
My code in Main Activity:
DatabaseReference databaseReference;
RecyclerView recyclerView;
ArrayList<Menu> menuList;
EditMenuAdapter editMenuAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_menu);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
menuList = new ArrayList<Menu>();
databaseReference = FirebaseDatabase.getInstance().getReference().child("menu");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Menu menu = dataSnapshot1.getValue(Menu.class);
menuList.add(menu);
}
editMenuAdapter = new EditMenuAdapter(EditMenuActivity.this, menuList);
recyclerView.setAdapter(editMenuAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(EditMenuActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
});
My adapter class:
public class EditMenuAdapter extends RecyclerView.Adapter<EditMenuAdapter.MyViewHolder> {
Context context;
ArrayList<Menu> menuArrayList;
public EditMenuAdapter(Context c, ArrayList<Menu> menus) {
context = c;
menuArrayList = menus;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.menu_list_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.dishNameTextView.setText(menuArrayList.get(position).getDishName());
holder.dishPriceTextView.setText(menuArrayList.get(position).getDishPrice());
}
#Override
public int getItemCount() {
return menuArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView dishNameTextView;
TextView dishPriceTextView;
Switch dishActiveSwitch;
public MyViewHolder(View view) {
super(view);
dishNameTextView = (TextView) view.findViewById(R.id.dishNameTextView);
dishPriceTextView = (TextView) view.findViewById(R.id.dishPriceTextView);
dishActiveSwitch = (Switch) view.findViewById(R.id.dishActiveSwitch);
}
}
}
The layout resource file is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditMenuActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="397dp"
android:layout_height="599dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/doneButton"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:text="Done"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/recyclerView" />
The log shows: E/RecyclerView: No adapter attached; skipping layout. No data is displayed.
Only the switch is being displayed on the screen. Please help!
Create instance of adapter in onCreate and attach it to RV:
protected void onCreate(Bundle savedInstanceState) {
...
editMenuAdapter = new EditMenuAdapter(this, new ArrayList<>());
recyclerView.setAdapter(adapter);
...
}
In the response of Firebase onDataChange:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
editMenuAdapter.setItems(menuList);
runOnUiThread(() -> editMenuAdapter.notifyDataSetChanged());
}
I am using a ListView inside my Fragment. I also have an EditText and a Button. So every time I click on my Button I take the content of my EditText how can I refresh my ListView every time I add a friend in my database without having to go into another Fragment and comeback.
Here is my fragment.
public class ContactFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_contact, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView list = getView().findViewById(R.id.contactframe);
auth = FirebaseAuth.getInstance();
final User user = new User();
bouton = getView().findViewById(R.id.search_btn);
email = getView().findViewById(R.id.search_field);
bouton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!email.getText().toString().trim().equals(auth.getCurrentUser().getEmail().toString().trim())) {
user.addFriend(auth.getCurrentUser().getUid(), email.getText().toString().trim());
email.setText("");
} else {
Toast.makeText(getActivity(), "Action refusé", Toast.LENGTH_LONG).show();
}
}
});
contactList = new ArrayList<User>();
mDatabase = FirebaseDatabase.getInstance().getReference("User").child(auth.getCurrentUser().getUid().toString())
.child("contact");
mDatabase.addListenerForSingleValueEvent(valueEventListener);
adaptor = new ContactAdaptor(getActivity(), contactList);
list.setAdapter(adaptor);
}
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
contactList.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User ami = snapshot.getValue(User.class);
contactList.add(ami);
}
adaptor.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
}
And my Adapter
public class ContactAdaptor extends ArrayAdapter<User> {
private LayoutInflater mInflater;
ArrayList<User> myList;
public ContactAdaptor(FragmentActivity activity, List<User> myList) {
super(activity, 0, myList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
User item = (User) getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_contact, parent, false);
}
TextView username = (TextView) convertView.findViewById(R.id.text_view_contact_username);
TextView email = (TextView) convertView.findViewById(R.id.contact_email);
username.setText(item.username);
email.setText(item.email);
return convertView;
}
}
The layout file is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Editext for Search -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:layout_marginTop="33dp"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Chercher içi"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:textColor="#999999"
android:textSize="16sp" />
<Button
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/search_field"
android:layout_marginEnd="60dp"
android:text="Ajouter" />
</RelativeLayout>
<ListView
android:id="#+id/contactframe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:layout_marginRight="16dp"
android:scrollbarSize="4dp"
android:scrollbarThumbVertical="#drawable/scrollbar"
android:scrollbars="vertical"
tools:context="com.android.pfe.fragment.ContactFragment"></ListView>
</LinearLayout>
You have used addListenerForSingleValueEvent which fetches the data for a single time and do not keep the underlying connection open to listen to any data change in firebase side.
You just have to use the addValueEventListener instead of addListenerForSingleValueEvent like the following.
mDatabase = FirebaseDatabase.getInstance().getReference("User").child(auth.getCurrentUser().getUid().toString())
.child("contact");
// This is where you should use the addValueEventListener instead of addListenerForSingleValueEvent
mDatabase.addValueEventListener(valueEventListener);
I am copying the portion which is helpful here from the firebase documentation.
In some cases you may want a callback to be called once and then
immediately removed, such as when initializing a UI element that you
don't expect to change. You can use the addListenerForSingleValueEvent()
method to simplify this scenario: it triggers once and then does not
trigger again.
Hope that will fix your problem.
I have created a Recycler view in my fragment_add_friends.xml like below
<android.support.v7.widget.RecyclerView
android:id="#+id/all_user_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
and I created all_user_display_layout.xml file for display each user like below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/all_user_image">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/all_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="full name"/>
<TextView
android:id="#+id/all_user_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="user status"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In my AddFriendsFragment.java I got the recycler view like below in my on create view method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_add_friends, container, false);
all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
all_user_list.setHasFixedSize(true);
all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));
return v;
}
and I have created a helper class that have Strings name, status,
image and there getters setters and constructor and empty construcor because I have to retrieve those data and xml file those things in is all_user_display_layout.xml
and I got the database reference like below
databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
and I create the onViewCreated method like below
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
after that what are the things that I have to do to get data from
fireabse to recycler view
please help me im new to these stuff
Assuming that users node is a direct child of your Firebase database root, to get the name, image and status, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List <String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String image = ds.child("image").getValue(String.class);
String status = ds.child("status").getValue(String.class);
list.add(name + " / " + image + " / " + status);
Log.d("TAG", name + " / " + image + " / " + status);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
Hemal / https... / Busy
Jake Stewart / https... / Busy
Remove these lines from onCreateView
all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
all_user_list.setHasFixedSize(true);
all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));
Add the following code in onViewCreated
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FirebaseRecyclerViewAdapter<<Your-Helper-Class>, ViewHolder> adapter;
ref = new Firebase("https://<yourapp>.firebaseio.com");
RecyclerView recycler = (RecyclerView) findViewById(R.id.all_user_list);
recycler.setHasFixedSize(true);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new FirebaseRecyclerViewAdapter<<Your-Helper-Class>, ViewHolder>(<Your-Helper-Class>.class, android.R.layout.all_user_display_layout.xml, ViewHolder.class, mRef) {
public void populateViewHolder(ViewHolder viewHolder, <Your-Helper-Class> helper) {
Picasso.with(context).load(helper.getImage()).into(viewHolder.image);
viewHolder.name.setText(helper.getName());
viewHolder.status.setText(helper.getStatus());
}
};
recycler.setAdapter(mAdapter);
}
private static class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView name;
TextView status;
public ChatMessageViewHolder(View itemView) {
super(itemView);
image = (TextView)itemView.findViewById(android.R.id.all_user_image);
name = (TextView)itemView.findViewById(android.R.id.all_user_name);
status = (TextView) itemView.findViewById(android.R.id.all_user_status);
}
}
Also use Picasso for loading image in imageview. Add these lines in your build.gradle.
compile 'com.squareup.picasso:picasso:2.5.2'
I have a ListView with 3 TextViews and a radio button in each row. I retrieve a certain state from my firebase database and show it in the radio button. I just don't know how to access the radio button to change its state. I know i should use a custom adapter but i don't how to. Can someone help ?
This is my code for the time being :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grille);
listView = (ListView) findViewById(R.id._afficher);
bus = new Bus(ThreadEnforcer.MAIN);
bus.register(this);
listView.addHeaderView(getLayoutInflater().inflate(R.layout.header, null, false));
loadData();
}
private void loadData(){
DatabaseReference mDB = FirebaseDatabase.getInstance().getReference("VFL");
mDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
MatrixCursor matrixCursor= new MatrixCursor(columns);
startManagingCursor(matrixCursor);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapsht : snapshot.getChildren()){
String s = snapsht.child("visiteur").getValue().toString();
if(s.equals(visiteur) || s.equals(visiteur1)){
matrixCursor.addRow(new Object[] {count.incrementAndGet(), snapsht.child("date").getValue().toString(),
snapsht.child("zone").getValue().toString(),snapsht.child("visité").getValue().toString() });
}
}
}
bus.post(matrixCursor);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Subscribe public void answerAvailable( MatrixCursor matrixCursor) {
// TODO: React to the event somehow!
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.ligne_afficher, matrixCursor, from, to, 0);
listView.setAdapter(adapter);
}
See this example using CustomAdapter extending BaseAdapter class:
1. listview activity layout
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.oxyzen.loc.YourActivity"
android:id="#+id/listView">
</ListView>
2. listview's single_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="tv1"
android:id="#+id/tv1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="tv2"
android:id="#+id/tv2"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="tv3"
android:id="#+id/tv3"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"
android:id="#+id/radioButton"/>
</LinearLayout>
3. (listview's activity) YourActivity.java
public class YourActivity extends AppCompatActivity implements ChildEventListener {
ListView listView;
CustomAdapter adapter;
DatabaseReference yourReference;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yourReference =FirebaseDatabase.getInstance().getReference().child("your_reference");
dialog = new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
setContentView(R.layout.activity_your);
listView = (ListView)findViewById(R.id.listView);
adapter = new CustomAdapter();
listView.setAdapter(adapter);
dialog.show();
yourReference.addChildEventListener(this);
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
dialog.dismiss();
adapter.addItem(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
4. CustomAdapter.java class for listview
public class CustomAdapter extends BaseAdapter {
ArrayList<DataSnapshot> values;
CustomAdapter(){
values = new ArrayList<>();
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return values.get(position);
//you can get the dataSnapshot by interacting your listview items as per position for use in listview's activity.
//You can return null also here.
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DataSnapshot snapshot = values.get(position);//use this snapshot to retrieve values for textviews and radiobutton.
OurViewHolder holder =new OurViewHolder(parent.getContext(),parent);
holder.tv1.setText(snapshot.getKey());
holder.tv2.setText("Text for textView 2");
holder.tv3.setText("Text for textView 3");
holder.button.setChecked(true);// manipulate your radio button as per your wish here. I just checked it for example.
return holder.itemView;
}
//Custom method: to notify and update adapter automatically if new child adds in firebase database.
void addItem(DataSnapshot snapshot){
values.add(snapshot);
notifyDataSetChanged();
}
//Custom class: Using OurViewHolder pattern keeps alive java's OOP concept i.e. one object per listview item.
//Inflate your single item's layout in here and find all components of item.
private class OurViewHolder {
View itemView;
TextView tv1,tv2,tv3;
RadioButton button;
OurViewHolder(Context context, ViewGroup parent){
itemView = LayoutInflater.from(context).inflate(R.layout.single_item_layout,parent,false);
tv1=(TextView)itemView.findViewById(R.id.tv1);
tv2=(TextView)itemView.findViewById(R.id.tv2);
tv3=(TextView)itemView.findViewById(R.id.tv3);
button=(RadioButton)itemView.findViewById(R.id.radioButton);
}
}
}