Updating the ListView in a ListFragment

33 views Asked by At

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>
0

There are 0 answers