0

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.

Krazi
  • 3
  • 4
  • to solve the last error, check this https://stackoverflow.com/questions/9280965/arrayadapter-requires-the-resource-id-to-be-a-textview-xml-problems – Peter Haddad Jan 28 '18 at 21:34
  • I have checked the post and from what i understand i can only use one textview using this method. How can i get more than one textview to work? – Krazi Jan 28 '18 at 22:56

2 Answers2

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

tanni tanna
  • 544
  • 4
  • 12
  • ListvViewMessages.add? there no add(); method – Krazi Jan 28 '18 at 19:20
  • sorry ListvViewMessages.add(messagesListDataModel); – tanni tanna Jan 28 '18 at 19:24
  • i get this error: Process: com.brunelcs.group13.anyquestions, PID: 11454 com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.brunelcs.group13.anyquestions.MessagesListDataModel – Krazi Jan 28 '18 at 20:02
  • on this line: MessagesListDataModel messagesListDataModel = dataSnapshot.getValue(MessagesListDataModel.class); – Krazi Jan 28 '18 at 20:02
  • chatroomsref = FirebaseDatabase.getInstance().getReference("Chatrooms").child("1234"); also as i said change variable names in model class. – tanni tanna Jan 28 '18 at 20:32
  • I dont see why i need to change the variable names to msg and name as they are already called the same in the model, adapter and main? can you also take a look at what ive done. – Krazi Jan 28 '18 at 21:23
  • ive changed them to lower case if that what you were after. – Krazi Jan 28 '18 at 21:25
  • I dont understand why it says resource ID has to be a textview? i though resource ID's were Ints? – Krazi Jan 28 '18 at 21:26
  • E/ArrayAdapter: You must supply a resource ID for a TextView – Krazi Jan 28 '18 at 21:27
  • Share xml file chat_messages_layout. Firebase requires variable name to match with that in database, – tanni tanna Jan 28 '18 at 21:32
  • XML seems fine.. is it because i have other fields and button that i want to implement later?... actually it isnt as ive removed the other stuff still same error. DO you mean that the Textview names have to be the same as in Firebase? – Krazi Jan 28 '18 at 22:08
  • No no, what is line 437 in arrayadapter? – tanni tanna Jan 28 '18 at 22:20
  • @Krazi You're not using a Custom ArrayAdapter class, and the constructor you called requires the resource layout *only be a TextView* – OneCricketeer Jan 28 '18 at 22:24
  • Agree with cricket_007, read this https://stackoverflow.com/questions/9280965/arrayadapter-requires-the-resource-id-to-be-a-textview-xml-problems – tanni tanna Jan 28 '18 at 22:28
0

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • fetch data is empty, i was gonna use a mthod for getting the data. – Krazi Jan 28 '18 at 23:01
  • Also my adapter takes in : public MessagesListAdapter(Context context, int resource, ArrayList dataModels). when i try set the resouce it wont let me and implementing the constructor gives an error. – Krazi Jan 28 '18 at 23:03
  • this constructor takes in the id of the listview and not the resource files for the listview – Krazi Jan 28 '18 at 23:07
  • this really doesnt make sense to me, could you elaborate? – Krazi Jan 28 '18 at 23:15
  • Look at this example. Your constructor needs changed. That resource does not need passed, and it is not the ID of the LIstView, even if it was. It would be an `R.layout` resource. https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView#defining-the-adapter – OneCricketeer Jan 29 '18 at 01:04
  • Thank you so much this worked, ive been struggling with this for days. in this case i dont understand why other peoples guide do it the way it was done it mine and it worked for them but not me. – Krazi Jan 29 '18 at 15:04
  • could you maybe help me with this? https://stackoverflow.com/questions/48508013/android-studio-firebase-increment-the-value-of-an-intusing-a-button-from-a-custo?noredirect=1#comment84011153_48508013 – Krazi Jan 29 '18 at 22:16