TextView not getting set upon Fragment creation

how to add fragment in activity in android example
android fragment tutorial with example
android fragment example source code
android multiple fragments in one activity example github
android multiple fragments in one activity example androidhive
fragment android example
android multiple fragments in same container
dynamic fragment in android

This is my first question on Stack Overflow, so apologies in advance if I'm asking in an improper way.

I'm trying to create a basic app in Kotlin, wherein I have a hamburger menu with some fragments in it. When the user clicks on the HomeFragment, I want to display a welcome message with his name (stored in a Shared Preferences object).

However, each time I click on the menu button to open the fragment, it crashes - even if I remove the whole username/shared prefs thing and just try to set some plain text.

Here is my HomeFragment.kt file:

package com.urmilshroff.kotlindemo

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_home.*


private const val ARG_PARAM1="param1"
private const val ARG_PARAM2="param2"

class HomeFragment:Fragment()
{
    private var param1:String?=null
    private var param2:String?=null
    private var listener:OnFragmentInteractionListener?=null

    override fun onCreate(savedInstanceState:Bundle?)
    {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1=it.getString(ARG_PARAM1)
            param2=it.getString(ARG_PARAM2)
        }

    }

    override fun onCreateView(inflater:LayoutInflater,container:ViewGroup?,
                              savedInstanceState:Bundle?):View?
    {
        super.onCreate(savedInstanceState)

        val username=SharedPrefObj.getUsername(this.activity!!)
        textViewHello.text="Hi there, $username!"

        return inflater.inflate(R.layout.fragment_home,container,false)
    }

    fun onButtonPressed(uri:Uri)
    {
        listener?.onFragmentInteraction(uri)
    }

    override fun onAttach(context:Context)
    {
        super.onAttach(context)
        if(context is OnFragmentInteractionListener)
        {
            listener=context
        }
        else
        {
            throw RuntimeException(context.toString()+" must implement OnFragmentInteractionListener")
        }
    }

    override fun onDetach()
    {
        super.onDetach()
        listener=null
    }

    interface OnFragmentInteractionListener
    {
        fun onFragmentInteraction(uri:Uri)
    }

    companion object
    {
        @JvmStatic
        fun newInstance()=
                HomeFragment().apply {
                    arguments=Bundle().apply {
                        putString(ARG_PARAM1,param1)
                        putString(ARG_PARAM2,param2)
                    }
                }
    }
}

My fragment_home.xml, just in case:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textViewHello"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:fontFamily="monospace"
            android:textAlignment="center"
            android:textColor="@color/colorAccent"
            android:textSize="30sp"
            app:layout_constraintBottom_toTopOf="@+id/textViewDesc"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.993" />

        <TextView
            android:id="@+id/textViewDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="240dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:fontFamily="monospace"
            android:text="@string/text_view_desc"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.503"
            app:layout_constraintStart_toStartOf="parent" />

    </android.support.constraint.ConstraintLayout>
</FrameLayout>

Crash log:

09-17 00:19:24.968 25279-25279/com.urmilshroff.kotlindemo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.urmilshroff.kotlindemo, PID: 25279
    java.lang.IllegalStateException: textViewHello must not be null
        at com.urmilshroff.kotlindemo.HomeFragment.onCreateView(HomeFragment.kt:37)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

It says that textViewHello must not be null, so I tried making it nullable yet it crashes. Not sure what's wrong. Any help is much appreciated, thanks!

textViewHello has not been initialized.

Initialise it like this:

val rootView = inflater.inflate(R.layout.fragment_home,container,false) 
val textViewHello: TextView = rootView.findViewById(R.id.textViewHello) as TextView

Add the above line before setting text on textview

final onCreateView will look like this:

    super.onCreate(savedInstanceState)
    val rootView = inflater.inflate(R.layout.fragment_home,container,false) 
    val username=SharedPrefObj.getUsername(this.activity!!)
    val textViewHello: TextView = rootView.findViewById(R.id.textViewHello) as TextView
    textViewHello.text="Hi there, $username!"
    return rootView;

TextView not visible in Fragment?, Clearly, the TextView is still getting created. But i have figured out that the textview is there but it is hiding under the extended toolbar/actionbar(because of Or you can even contract the ActionBar by sliding on it upward to reveal your textview. Set your ViewPager height to an absolute value instead of  You have to access text view from your third fragment where you used it in its layout. Then access that object from your fragment activity. in your fragment do something like this. TextView mTextView; mTextView = (TextView)getView().findViewById(R.id.your_text_view); Create a function like this

You are using Kotlin Android Extentions in your project, so no need to call findViewById method anymore.

All you need to do is change your code to:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    super.onCreate(savedInstanceState)
    return inflater.inflate(R.layout.fragment_home, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val username = SharedPrefObj.getUsername(this.activity!!)
    textViewHello.text = "Hi there, $username!"
}

Creating and Using Fragments · codepath/android_guides Wiki , Hiding and showing relevant fragments using the fragment manager. android:​orientation="vertical" > <TextView android:id="@+id/textView1" Use onCreate for any standard setup that does not require the activity to be fully created @​Override set arguments; Methods - Activity can call methods on a fragment instance  Let's say I want to change the TextView inside one of the fragments. So I added this on my StartActivity.java, under onCreate: TextView textview = (TextView) findViewById(R.id.textView1); textview.setText("HI!"); When I start my app, it crashes. Can somebody point me to the right direction?

put below line in onViewCreated method. You need to override that method.

textViewHello.text="Hi there, $username!"

this will set the textview after it has been initiated in onCreateView

Create a fragment, You can think of a fragment as a modular section of an activity, which has its own If you have not used the Support Library before, set up your project to use the v4 library by One difference when creating a Fragment is that you must use the In fact, this is the only callback you need in order to get a fragment running. Put information from mySQL into a Fragment textView's before onCreate Tag: android , mysql , json , android-fragments My application currently loads the fragment and when I try to load the profile of the person during the fragments onCreate(), it ends up pulling after the fragment is made and none of my textviews can change.

You need use it in onViewCreated.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.qr_my_fragment, container, false) }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    init()
}

private fun init() {
    setQRCode()
    initToolbar()
    clickEvents()
}

Two fragments in one activity, The support for fragments was not introduced until Android 3.0. Right-click on the layout package under res and selecting the New → Other. </EditText></​RelativeLayout>Creating the First Fragment ClassAditionally to a UI layout, is going to need to get the text from the EditText view send them to the two fragment UI. Android TextView is a user interface element show text (label) to users in the application. You can change TextView dynamically (programmatically). View class is the parent class of android.widget.TextView. TextView can Create by declaring it inside a layout XML file or by instantiating it programmatically.

You are trying to call method setText, but your TextView object actually is null. You need to initialize. Before set text, you should make some step. 1. Inflate view in variable

val view = inflater.inflate(R.layout.fragment_home,container,false)

2. Find and connect xml object with class variable

val textView: TextView = view.findViewById(R.id.textViewHello)

3. Now, you can call setText

textView.setText("Example text")

Just modify your onCreateView method

val view = inflater.inflate(R.layout.fragment_home,container,false)
val textView: TextView = view.findViewById(R.id.textViewHello)
textView.setText("Example text")

1.1: Creating a Fragment with a UI · GitBook, Create a Fragment to use as a UI element that gives users a "yes" or "no" choice. This is a useful technique for consolidating a set of UI elements (such as textView (the fragment_header in the layout) depending on the radio button choice: Replace the TODO: Get the FragmentManager comment in the above code  As previously discussed, support for fragments was not introduced until Android 3.0. This means that for applications that make use of fragments to be compatible with older versions of Android, use must be made of version 4 of the Android Support Library.

Get Value from the EditText and Set value to the TextView, Get Value from the EditText and Set value to the TextView. In this tutorial we will learn how to take input from the user through EditText view in Android and Whenever we click on any button or submit any form, the backend code decides what action to The view created in XML is used in Java to manipulate it dynamically. Why Your TextView or Button Text Is Not Updating. Why does changing the text for a TextView using the setText method not work sometimes? New Android developers sometimes fail to understand why changing the text does not appear to work. The text not updating also applies to other Views as well, such as the EditText and Button. Why this happens

Set text for textview that is in a fragment from another fragments , Set text for textview that is in a fragment from another fragments I am trying to set text in a textview from the onClick method of a fragment but I keep getting EditText.setText(java.lang.CharSequence)' on a null object reference setText("​Text"); the textView is not yet created and binded to the fragment. The fragment will be re-created, and the user will have to scroll once again to the 70th item. I don’t think i want to start messing with bundles and back stack problems. So i created a new

Android Fragments Tutorial: An Introduction with Kotlin , In this Android Fragments with Kotlin tutorial you will learn the fundamental concepts of fragments while creating an app that As the name would suggest, fragments are not independent entities, but are tied Hang on, you'll get the answer to that later! You can see this in the TextView with the ID name : Generally, we develop the layout for an Android application by creating the XML file. These are called static layouts. Yes, because you can not add/delete any View Type in XML on runtime. Dynamic

Comments
  • Thanks for the quick response, it worked perfectly😁