简体   繁体   中英

firebase Retrieve data into custom Listview and Custom Adapter

I have created a custom listview and a custom adapter. I want to load the data from firebase but i dont know how to. I have gone through a lot of posts but it doesnt help me. I need someone to walk me through.

What I need is for someone to tell me how i can retrieve the data;

This is the structure

Data Model:

public class MessagesListDataModel {
 private String uid;
 private String msg;

 public MessagesListDataModel(){

 }

public MessagesListDataModel(String UID, String Message){
    this.uid = UID;
    this.uid = Message;

}//instance of datamodel

public String getUID(){
    return uid;
}

public String getMessage(){
    return msg;
}

}

Custom Adapter:

public class MessagesListAdapter extends ArrayAdapter<MessagesListDataModel> {

private ArrayList<MessagesListDataModel> dataModels;

public MessagesListAdapter(Context context, int resource, ArrayList<MessagesListDataModel> dataModels){
    super(context, resource, dataModels);
    this.dataModels = dataModels;

}


public View getView(int position, View convertView, ViewGroup parent){

    View v = convertView;

    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.chat_messages_layout, null);
    }

    MessagesListDataModel MessagesListDataModel = dataModels.get(position);

    if (MessagesListDataModel != null) {

        // These TextViews are created in the XML files defined.

        TextView uid = (TextView) v.findViewById(R.id.textViewMessage);
        TextView message = (TextView) v.findViewById(R.id.textViewUserID);


        // check to see if each individual textview is null.
        // if not, assign some text!
        if (uid != null){
            uid.setText(MessagesListDataModel.getUID());
        }
        if (message != null){
            message.setText(MessagesListDataModel.getMessage());
        }

    }

    // the view must be returned to our activity
    return v;

}
}

In Main:

chatroomsref = FirebaseDatabase.getInstance().getReference("Chatrooms");

    ///////
    ListViewMessages = (ListView) findViewById(R.id.chatRoomMessagesListview);



ArrayAdapter<MessagesListAdapter> arrayAdapter = new ArrayAdapter<MessagesListAdapter>(this, R.layout.chat_messages_layout,messages);
    ListViewMessages.setAdapter(arrayAdapter);

    chatroomsref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            fetchData();
        }

        @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) {

        }
    });

fetchData:

I need to know how to fetch the data so that it iterates through all the chat rooms witha unique id and them takes that data from the database and assign it to those textviews and displays the data so that i can run this function in the database reference. but i dont know how?

So what i did in main is :

room_name = getIntent().getExtras().get("room_name").toString();

the listview which i have of all the chatrooms has a click even listener where when the room is clicked it passes on the room name as a string into the activity where all of this is supposed to happen. So i took that variable to be passed retrieved so that the reference is updated when the specific room is entered:

chatroomsref = FirebaseDatabase.getInstance().getReference("Chatrooms").child(room_name);

But now i get this error:

Process: com.brunelcs.group13.anyquestions, PID: 14662 java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:437)

XML:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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">

<TextView
    android:id="@+id/textViewUserID"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="12dp"
    android:layout_marginTop="14dp"
    android:layout_weight="1"
    android:text="UserID"
    android:textAlignment="viewStart"
    android:textColor="@color/colorPrimary"
    android:textSize="12sp" />

<TextView
    android:id="@+id/textViewDateTime"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/textViewUserID"
    android:layout_marginStart="11dp"
    android:layout_toEndOf="@+id/textViewUserID"
    android:text="DateTime"
    android:textAlignment="center"
    android:textColor="@color/colorPrimary"
    android:textSize="12sp" />

<TextView
    android:id="@+id/textViewMessage"
    android:layout_width="500dp"
    android:layout_height="50dp"
    android:layout_alignStart="@+id/textViewUserID"
    android:layout_below="@+id/textViewUserID"
    android:text="Message"
    android:textAlignment="viewStart"
    android:textSize="15dp" />

<Button
    android:id="@+id/button5"
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:layout_alignStart="@+id/textViewMessage"
    android:layout_below="@+id/textViewMessage"
    android:text="Replies" />

<Button
    android:id="@+id/button6"
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:layout_alignBottom="@+id/button5"
    android:layout_alignStart="@+id/textViewDateTime"
    android:text="Like" />

<TextView
    android:id="@+id/textView11"
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/button6"
    android:layout_marginBottom="13dp"
    android:layout_toEndOf="@+id/button6"
    android:text="24"
    android:textAlignment="center" />

Also shouldnt i use:

//for (DataSnapshot child : dataSnapshot.getChildren()) {

}

and retrieve the data there for each child of the room? But i dont know how to.

public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            //fetchData();
           MessagesListDataModel messagesListDataModel = 
           dataSnapshot.getValue(MessagesListDataModel.class);    
           ListvViewMessages.add(messagesListDataModel);
           arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
             // do similar to add 
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
                   //remove the entry from array list if required
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

Important is the data structure variables should match with the variables name in model class. instead of private String UID; private String Message;

use private String msg; private String name;

First, I recommend you use Firebase UI for populating a list

Anyway, the constuctor you are using is wrong.

new ArrayAdapter<MessagesListAdapter>(this, R.layout.chat_messages_layout,messages);

Read the documentation... It says the second parameter is a resource that is only a TextView

resource int: The resource ID for a layout file containing a TextView to use when instantiating views.

Your XML file is a RelativeLayout , not a TextView , hence the error.


So, you defined a custom adapter, but you never make one doing this.

new MessagesListAdapter(this, messages);

And in order to use that correctly, you'll want to implement this constructor that doesn't use a resource ID since you already are using it in getView of the adapter.

public MessagesListAdapter(Context context, ArrayList<MessagesListDataModel> dataModels){
    super(context, 0, dataModels);
    // This line isn't necessary, either. The third parameter of super() already sets an internal arraylist
    this.dataModels = dataModels;  
}

Its not clear what fetchData() is actually doing, but you need to iterate over the DataSnapshot children there instead.

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