Home > Back-end >  How to build recyclerView without a predefined Model class
How to build recyclerView without a predefined Model class

Time:02-23

I am having a database (Firebase), which contains details of users, where each user can add any amount of personnel details. Like one person can add only name and age while another user can add a name, age, and address.

I am also building an android app that displays those details using a recyclerView.I am using a basic recycler view.

Now the problem is a recyclerView requires a pre-defined model class with pre-defined getters and setters, but my database is dynamic and can have any number of values.

Like some users may only have a name and age while others may have a name, age, address. For the first user, we only have to define the name, age, and define getters and setters, but for the second user we have to define the extra address variable and assign getters and setters. Adding them pre-hand is not a good idea because users can add any number of details.

I need a recyclerView that can show any number of values, how should I do that.

PS: I think no code is needed because I am using a basic recycle view. Please tell me if I should post the code too.

CodePudding user response:

If there is a chance in which some fields may remain uninitialized due to the fact the users might leave some fields empty, then when it comes to displaying data, never try to display the value of a field if it can be potentially null. Always check against nullity before accessing it.

String address = user.getAddress();
if(address != null) {
    addressTextView.setText(address);
}

CodePudding user response:

All the fields optionals should be nullable. So in the case that you don't receive any of the optionals fields you won't get an exception. I think your model should be like this:

data class User(
    val name: String,
    val age: Int,
    val address: String?
    ...
)

But as Alex said, don't forget check this nullability before use "address" value.

  • Related