简体   繁体   中英

How to display the firebase data in listview?

I tried to receive the data from firebase using others people code but the app will be force stop. And I dont understand their code because I'm still new in android development. Here my code that only display the data in logcat but I will it display into a listview pls help me thanks.

This is 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:textAlignment="center"
        android:textSize="25sp"
        android:text="Time Table"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvUserInfo"/>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="11dp" />

</LinearLayout>

This is the java class:

DatabaseReference dref;
ListView listview;
ArrayList<String> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference usersRef = rootRef.child("Time");
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String email = ds.child("email").getValue(String.class);
                String time = ds.child("time").getValue(String.class);
                Log.d("TAG", email + " / " + time); // logcat check value
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    usersRef.addListenerForSingleValueEvent(eventListener);
}

This picture is the firebase value that i want to display in list view (email and time)

The thing I want to do is display the data from firebase in listview

You can use FirebaseListAdapter for display data in list.

Like :

Firebase ref = new Firebase("https://<yourapp>.firebaseio.com");
     ListAdapter adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class, android.R.layout.two_line_list_item, mRef)
     {
         protected void populateView(View view, ChatMessage chatMessage)
         {
             ((TextView)view.findViewById(android.R.id.text1)).setText(chatMessage.getName());
             ((TextView)view.findViewById(android.R.id.text2)).setText(chatMessage.getMessage());
         }
     };
     listView.setListAdapter(adapter);

You have almost done that you just need Recyclerview to display data here is a guide on how to display the data in the list.

Create a model and then store the email and time in this model.

class Sample{

 String time;
 String email;

 public void setEmail(String email){
   this.email = email;
 }

 public void setTime(String time){
   this.time = time;
 }

}

now store the data from firebase into this model.

@Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<Sample> sampleList = new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                Sample obj = new Sample();
                String email = ds.child("email").getValue(String.class);
                String time = ds.child("time").getValue(String.class);
                obj.setEmail(email);
                obj.setTime(time);
                sampleList.add(obj);
                Log.d("TAG", email + " / " + time); // logcat check value
            }
        }

now follow this guide to create recyclerview and pass the list created above to recyclerview to inflate the list.

https://guides.codepath.com/android/using-the-recyclerview

EDit:

add dependency:

implementation 'com.android.support:recyclerview-v7:27.1.1'

now add recyclerview where you want to add it like in fragment or activity.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvSample"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

now its time to add item view for a single row:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        >

    <TextView
        android:id="@+id/email"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        />

    <TextView
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:textSize="10sp"
        />

</LinearLayout>

now add an adapter for recyclerview to work.

    public class Adapter extends
    RecyclerView.Adapter<Adapter.ViewHolder> {

    List<Sample> list;

    Adapter(List<Sample> newList){
     this.list = newList;
    }    

    @Override
    public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.item_contact, parent, false);

        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(Adapter.ViewHolder viewHolder, int position) {
        // Get the data model based on position
        Sample obj = list.get(position);

        // Set item views based on your views and data model
        viewHolder.time.setText(obj.getTime());
        viewHolder.email.setText(obj.getEmail());
    }

    // Returns the total count of items in the list
    @Override
    public int getItemCount() {
        return list.size();
    }

public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView email;
        public TextView time;

        public ViewHolder(View itemView) {
            super(itemView);

            email = (TextView) itemView.findViewById(R.id.email);
            time = (TextView) itemView.findViewById(R.id.time);
        }
    }

}

now access the created recyclerview in your fragment and activity. like below and set properties and set adapter.

List<Sample> list = new ArrayList<>();
Adapter adapter = new Adapter(list);
rvSample.setLayoutManager(new LinearLayoutManager(this));
rvSample.setAdapter(adapter);

now when you get the data from firebase just add to existing list and notify the adapter.

@Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Sample> sampleList = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Sample obj = new Sample();
            String email = ds.child("email").getValue(String.class);
            String time = ds.child("time").getValue(String.class);
            obj.setEmail(email);
            obj.setTime(time);
            sampleList.add(obj);
            Log.d("TAG", email + " / " + time); // logcat check value
        }
        list.addAll(sampleList);
        adapter.notifyDataSetChanged();
    }

Try this code.. Recycler view make adapter for display ..

public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder> {
private List<User> mUserLsit = new ArrayList<>();
private Context mContext;

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
    return new ItemViewHolder(view);
}

public DisplayAllData(Context mContext, List<User> mUserLsit) {
    this.mContext = mContext;
    this.mUserLsit = mUserLsit;
}

@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    User user = mUserLsit.get(position);
    holder.mTvName.setText(user.name);
    holder.mTvEmail.setText(user.email);
    holder.mTvPwd.setText(user.pwd);
}

@Override
public int getItemCount() {
    return mUserLsit.size();
}

public class ItemViewHolder extends RecyclerView.ViewHolder {
    TextView mTvName, mTvEmail, mTvPwd;

    public ItemViewHolder(View itemView) {
        super(itemView);
        mTvEmail = itemView.findViewById(R.id.rlTvEmail);
        mTvName = itemView.findViewById(R.id.rlTvName);
        mTvPwd = itemView.findViewById(R.id.rlTvPwd);

    }
}
}

make activity..

public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_data);
    initView();
}

private void initView() {
    mFirebaseInstance = FirebaseDatabase.getInstance();
    mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");

    mRvData = findViewById(R.id.rvData);
    mTvEmpty = findViewById(R.id.dlTvEmpty);
    mRvData.setLayoutManager(new LinearLayoutManager(this));
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            mUserList.clear();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                User user = dataSnapshot1.getValue(User.class);
                mUserList.add(user);
            }
            allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
            mRvData.setAdapter(allDataAdapter);
            allDataAdapter.notifyDataSetChanged();
            if (mUserList.isEmpty())
                mTvEmpty.setVisibility(View.VISIBLE);
            else
                mTvEmpty.setVisibility(View.GONE);
        }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
}

and i hope you add internet permission into android manifest file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM