Search code examples
androidlistviewfirebasefirebase-realtime-databaseandroid-arrayadapter

Firebase Queries don't Show Data in Adapter


In my Application, I tried to get data in listview using simple queries with simple Adapters and FirebaseListAdapter, but the data ,which is selected, haven't shown in the listview, you can find FirebaseAdapter in comments in onCreateview, Code is as shown below:

package mainproject.mainroject.story;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.util.ArrayList;

import mainproject.mainroject.story.dummy.DummyContent.DummyItem;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ItemFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private ArrayList<String> musername = new ArrayList<>();
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemFragment() {
    }


    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static ItemFragment newInstance(int columnCount) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        ListView recyclerView = (ListView) view.findViewById(R.id.list);

//        // Set the adapter
//        if (view instanceof RecyclerView) {
//            Context context = view.getContext();
//            if (mColumnCount <= 1) {
//                recyclerView.setLayoutManager(new LinearLayoutManager(context));
//            } else {
//                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
//            }
//            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS, mListener));
////        }

        FirebaseDatabase mydatabase=FirebaseDatabase.getInstance();
        DatabaseReference myRef = mydatabase.getReference().child("UserDetail");
                Query query=FirebaseDatabase.getInstance().getReference().child("StoriesDetails").orderByChild("story_content").equalTo("story_content");

//The error said the constructor expected FirebaseListOptions - here you create them:
//        FirebaseListOptions<String> options = new FirebaseListOptions.Builder<String>()
//                .setQuery(query, String.class)
//                .setLayout(android.R.layout.simple_list_item_1)
//                .setLifecycleOwner(this)
//                .build();
//        FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(options) {
//            @Override
//            protected void populateView(View v, String  model, int position) {
//                TextView text = (TextView)view.findViewById(R.id.id);
//                text.setText(model);
//            }
//        };
        musername.add(String.valueOf(query));
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, musername);
        recyclerView.setAdapter(arrayAdapter);

//        myRef.addChildEventListener(new ChildEventListener() {
//            @Override
//            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//                GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
//                Map<String,String> map=dataSnapshot.getValue(genericTypeIndicator);
//                String value =map.get("Name");
//
////                musername.add(value);
////                arrayAdapter.notifyDataSetChanged();
//            }
//
//            @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) {
//
//            }
//        });
       return view;
    }

//    @Override
//    public void onDetach() {
//        super.onDetach();
//        mListener = null;
//    }
//
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(DummyItem item);
    }
}

layouts

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" />

</LinearLayout>

<?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:id="@+id/list"
    android:name="mainproject.mainroject.story.ItemFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="mainproject.mainroject.story.ItemFragment"
    tools:listitem="@layout/fragment_item" />

Solution

  • when you get data from firebase database used below code ...

       Query query=FirebaseDatabase.getInstance().getReference().child("StoriesDetails").orderByChild("story_content").equalTo("story_content");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
    
                for (DataSnapshot issue : dataSnapshot.getChildren()) {
    
                    musername.add(issue.getValue(User.class).name); // define your pojo class for getting firebase data.
                }
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, musername);
                recyclerView.setAdapter(arrayAdapter);
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    }