Making The Perfect Kickbutt Chat Fragment In Android And Kotlin Part 1 onCreateView() Overview21:25 PM, May 27 2025
What You Will Need
The Most Basic of Basic AssumptionsBefore you start, it is probably good to get acquainted with the things you will need for this project. I assume that you have a relatively powerful computer capable of doing Android programming. But I will give you a tip that I found along the way, and it is that if you don't have a capable computer, you may still be able to use a relatively current Android smartphone instead of running an emulator. You would likely want to do this if your Android version is very new. Although your computer will still need to be powerful enough to run the latest version of Android studio. I also assume you know some Kotlin for Android. That you're confident writing mutable and immutable variables, functions, and know how the general Android lifecycle of fragments work. Onward To The Technical StuffUnderstanding Key Variables in the Chat FragmentBefore we dive into defining our mutable (var) and immutable (val) variables, let’s get a better sense of what a few of these important fields are doing behind the scenes. We’re setting up several components that help power the chat experience: currentUserId: This is a read-only (val) variable that grabs the current user's ID from Firebase Authentication. Since it's a value that shouldn’t change while the fragment is alive, it's declared as val.
chatViewModel: This variable connects our fragment to the ChatViewModel, which helps manage UI-related data in a lifecycle-conscious way. For instance, it helps preserve chat messages even if the user rotates their screen.
chatAdapter: This is a custom adapter (we’ll look at it in more detail in a future article) that manages how our messages are displayed in a RecyclerView. Since we'll initialize it after the view is created, we use lateinit.
binding: This links our layout XML to the Kotlin code using View Binding. It’s also marked lateinit since we initialize it during onCreateView().
chatController: This handles logic for sending, receiving, and processing chat messages—essentially the brain behind our chat operations.
profileImageUri & senderName: These hold the user's profile image and name, both needed when sending messages or displaying user info.
chatRoomId: Stores the unique ID for the chat room, which helps us identify and separate conversations.
errorAndValidation: A utility object to help handle form validation and error display—very useful for keeping user input clean and friendly.
score & magnitude: These may be related to sentiment analysis or message scoring (based on the names). They're initialized with default values and can change, hence they’re var.
isProfileLoaded & isMessageObservable: Flags to track whether a profile has finished loading and whether the message stream is active.
A Quick Note on val, var, and VisibilityIn Kotlin, deciding whether to use val or var comes down to mutability—val means the reference can’t change, while var allows it. Similarly, choosing between private, public, or protected depends on what should be exposed to other parts of your app. If you're unsure, it’s best to default to private val for safety and clarity. We also use lateinit for variables that we can’t initialize right away (like UI elements or controllers that depend on the view being ready). It tells the compiler, “Trust me, I’ll initialize this before using it.” ✅ isLoggedIn() FunctionThis function checks if a user is currently logged in using Firebase. If no user is found (currentUser == null), it replaces the current fragment with a LoginFragment, redirecting the user to log in. If a user is unexpectedly present in an invalid state, it logs the issue using ErrorAndValidation and closes the current activity to prevent further access. This adds a security layer to ensure only authenticated users reach the chat UI. onCreateView()onCreateView is a lifecycle method in a Fragment. It’s responsible for inflating the layout (i.e., turning the XML layout file into a view hierarchy) and initializing components like UI elements, adapters, and LiveData observers. We get the current user’s ID from Firebase.
If no profile is found, we show a toast and navigate them away, likely back to a setup or discovery screen.
✅ Why this matters: This ensures that users can't start chatting without first completing a profile A ChatController is created to handle chat logic.
isLoggedIn() is presumably a method that verifies the user session or perhaps triggers some state check. (You might want to explain this if it's defined elsewhere.)
This sets up View Binding so we can access our layout elements in Kotlin without needing findViewById. Double-checks login status. If not logged in, user is redirected and the view is returned early to stop further code execution.
✅ Why this matters: Avoids crashes or weird behavior from unauthenticated users accessing chat features.
Starts the process of either getting or creating a chat room with the other user.
If something went wrong getting the user:
Ends the activity to prevent further interaction.
This listens to changes in the chatMessagesLiveData (likely a list of chat messages).
This is a custom method in your class to observe other LiveData or handle additional logic.
This returns the final view to Android so it can display it on the screen. So overall, this onCreateView method: Checks login and user profile status.
Handles navigation if any critical piece is missing (e.g., login or user profile).
