Change text from Textview to an Android Fragment

Asked

Viewed 5,449 times

3

I have a TextView within a Fragment (a tab). How do I change the text of this TextView? Here it is giving NullPointer

qtAllImagensLabel = (TextView)findViewById(R.id.qtAllImagensLabel);

qtAllImagensLabel.setText("texto");

I’ve tried to initialize the TextView within the onCreateView(), and I have tried to change the text within a Handler. When I try to change inside a Handler, it does not alter, but not the NullPointer

Edit: I start the variables globally and on onCreateView() make them receive the findViewById()

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_umclique_tab, container, false);

        qtAllImagensLabel = (TextView)findViewById(R.id.qtAllImagensLabel);
        qtAllVideosLabel = (TextView)findViewById(R.id.qtAllVideosLabel);
        qtAllAudioLabel = (TextView)findViewById(R.id.qtAllAudioLabel);

        return view;
}

So far so good, but I tried to set the text in and out of the onCreate(), within a Button, but not of.

Error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.tupinikimtecnologia.whatsappmediahidder/br.com.tupinikimtecnologia.whatsappmediahidder.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5140)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at br.com.tupinikimtecnologia.whatsappmediahidder.MainActivity.onCreate(MainActivity.java:103)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2170)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5140)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
            at dalvik.system.NativeStart.main(Native Method)

If I put inside a Handler, it does not error, but also does not alter the text.

Layout of the Fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/relative1"
        android:layout_marginBottom="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_descricao_label"
            android:id="@+id/textView" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/relative2"
        android:layout_weight="1"
        android:background="@drawable/umclique_tab_border">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/umclique_tab_titulo_imagem"
            android:id="@+id/imagensTituloLabel"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_qt_imagem"
            android:id="@+id/visEsconderLabel1"
            android:layout_below="@+id/imagensTituloLabel"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_qt_all_label"
            android:id="@+id/qtAllImagensLabel"
            android:layout_alignTop="@+id/visEsconderLabel1"
            android:layout_toRightOf="@+id/visEsconderLabel1"
            android:layout_marginLeft="5dp" />

        <Button
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:text="@string/umclique_tab_botao_revelar"
            android:id="@+id/mostrarButton1"
            android:layout_below="@+id/visEsconderLabel1"
            style="@style/ButtonVerdeMostrar"
            android:layout_toLeftOf="@+id/imagensTituloLabel"
            android:onClick="mostrarImagensUmCliqueTab" />

        <Button
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:text="@string/umclique_tab_botao_esconder"
            android:id="@+id/esconderButton1"
            android:layout_below="@+id/visEsconderLabel1"
            android:layout_toRightOf="@+id/imagensTituloLabel"
            style="@style/ButtonVermelhoEsconder"
            android:onClick="esconderImagensUmCliqueTab" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/relativeLayout"
        android:layout_weight="1"
        android:background="@drawable/umclique_tab_border">

        <Button
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:text="@string/umclique_tab_botao_revelar"
            android:id="@+id/mostrarButton2"
            android:layout_alignWithParentIfMissing="false"
            android:layout_below="@+id/visEsconderLabel2"
            android:layout_toLeftOf="@+id/textView6"
            style="@style/ButtonVerdeMostrar"
            android:onClick="mostrarVideosUmCliqueTab" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/umclique_tab_titulo_video"
            android:id="@+id/textView6"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_qt_video"
            android:id="@+id/visEsconderLabel2"
            android:layout_below="@+id/textView6"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_qt_all_label"
            android:id="@+id/qtAllVideosLabel"
            android:layout_alignTop="@+id/visEsconderLabel2"
            android:layout_toRightOf="@+id/visEsconderLabel2"
            android:layout_marginLeft="5dp" />

        <Button
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:text="@string/umclique_tab_botao_esconder"
            android:id="@+id/esconderButton2"
            android:layout_alignTop="@+id/mostrarButton2"
            android:layout_toRightOf="@+id/textView6"
            style="@style/ButtonVermelhoEsconder"
            android:onClick="esconderVideosUmCliqueTab" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/relativeLayout2"
        android:layout_weight="1"
        android:background="@color/preto">

        <Button
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:text="@string/umclique_tab_botao_revelar"
            android:id="@+id/mostrarButton3"
            android:layout_below="@+id/visEsconderLabel3"
            android:layout_toLeftOf="@+id/textView9"
            style="@style/ButtonVerdeMostrar" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/umclique_tab_titulo_audio"
            android:id="@+id/textView9"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_qt_audio"
            android:id="@+id/visEsconderLabel3"
            android:layout_below="@+id/textView9"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="@string/umclique_tab_qt_all_label"
            android:id="@+id/qtAllAudioLabel"
            android:layout_alignTop="@+id/visEsconderLabel3"
            android:layout_toRightOf="@+id/visEsconderLabel3"
            android:layout_marginLeft="5dp" />

        <Button
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:text="@string/umclique_tab_botao_esconder"
            android:id="@+id/esconderButton3"
            android:layout_below="@+id/visEsconderLabel3"
            android:layout_toRightOf="@+id/textView9"
            style="@style/ButtonVermelhoEsconder" />
    </RelativeLayout>

</LinearLayout>
  • 1

    In general to search for an element of a layout Fragment is made the findViewById in View which was inflated by LayoutInflater within the onCreateView and then returned as a result. If you are doing this, post the code and layout of this Fragment.

  • I’ve already edited @Wakim

1 answer

4


There’s been a mistake in that code, referring to Fragment but this code is being executed in a Activity correct? I say this because only the class Activity (apart from the Views) has the method findViewById, in documentation class Fragment does not have this method.

The problem you’re encountering is because of life cycle, the method onCreateView in Activity is called to inflate the layout of Activity, which in turn if you have the tag declaration <fragment> correct, will initiate the Fragment calling his onCreate and subsequently the onCreateView.

The cycle would be something like:

  1. Activity.onCreate
  2. Activity.onCreateView
  3. Fragment.onAttach
  4. Fragment.onCreate
  5. Fragment.onCreateView

More details on Fragment Lifecycle

And the moment you do findViewById by elements of the Fragment in the method onCreateView, it does not yet exist and is not built. Therefore it does not find the elements, and moreover, the Root View of Activity not built entirely, just inflated. So you can’t use the findViewById, would have to use view.findViewById to find elements of this layout and not the layout of Fragment.

Looking at this layout, to use Fragment would have to have a layout for the Activity this way (I believe you are using it so right?):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/id_do_fragment"
        android:name="pacote.da.classe.ClasseDoFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:tag="@string/tag_do_fragment" />
</FrameLayout>

You would use this layout as being from Activity and within the layout of Fragment what you put in the question.

You will have to change the approach.

In that case I suggest two simple (recommend the first):

  1. Migrate these references to the Fragment, using the method onCreateView of Fragment to initialize them. The code would look very similar to the current one, except for the changes of logic that is recommended, because it ends up delegating some responsibilities to the Fragment. Making code less coupled (if done the right way) and more modularizable.

  2. Or use the method onViewCreated of Fragment to notify the Activity (using Listener or the Activity) that the View was built and it is safe to access it.

    No Fragment:

     @Override
     public void onViewCreated (View view, Bundle savedInstanceState) {
         ((SuaActivity) getActivity()).onFragmentViewCreated(view); // Metodo que deve ser implementado na Activity
     }
    

    Na Activity:

     public void onFragmentViewCreated(View view) {
         // Iniciar os campos buscando no layout do Fragment
         qtAllImagensLabel = (TextView) view.findViewById(R.id.qtAllImagensLabel);
         qtAllVideosLabel = (TextView) view.findViewById(R.id.qtAllVideosLabel);
         qtAllAudioLabel = (TextView) view.findViewById(R.id.qtAllAudioLabel);
     }
    
  • With your answer I realized that I was using the wrong class, now it’s working, must be hours without drinking coffee...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.