Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

I have a BlankFragment

package com.hfad.addingafragmenttoframelayout;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.w3c.dom.Text;


/**
 * A simple {@link Fragment} subclass.
 */
public class BlankFragment extends Fragment {


    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("message","onCreateView() of BlankFragment");
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

    public void setText(String textToBeSet){
        TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText);
        tv.setText(textToBeSet);
    }

}

and it's layout is:

<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"
    tools:context="com.hfad.addingafragmenttoframelayout.BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:id="@+id/fragmentText"/>

</FrameLayout>

Here is the MainActivity

package com.hfad.addingafragmenttoframelayout;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //BlankFragment bf = new BlankFragment();
        //getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, bf).commit();

        BlankFragment bf = new BlankFragment();
        bf.setText("hello world");
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, bf).commit();


    }




}

and here is the layout of MainActivity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hfad.addingafragmenttoframelayout.MainActivity"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fragment_container"
        />


</LinearLayout>

In the onCreate method of activity I am adding fragment to layout. This works fine unless I try to change the Text using setText method.

And I get this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                           at com.hfad.addingafragmenttoframelayout.BlankFragment.setText(BlankFragment.java:35)
                                                                                           at com.hfad.addingafragmenttoframelayout.MainActivity.onStart(MainActivity.java:29)

referring to this line

TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText);

Can somebody explain what's causing this exception?

like image 460
user4913383 Avatar asked May 12 '16 05:05

user4913383


3 Answers

Don't

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d("message","onCreateView() of BlankFragment");
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_blank, container, false);
}

public void setText(String textToBeSet){
    TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText);
    tv.setText(textToBeSet);
}

Do

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
{

    View RootView = inflater.inflate(R.layout.fragment_blank, container, false);

    TextView tv = (TextView)RootView.findViewById(R.id.fragmentText);
    tv.setText("HI");

    return RootView;
}
like image 131
IntelliJ Amiya Avatar answered Nov 07 '22 03:11

IntelliJ Amiya


Here:

bf.setText("hello world");

line causing issue, becuase calling setText method of Fragment before adding Fragment in FragmentManager.

Call setText method after adding bf Fragment:

    getSupportFragmentManager().beginTransaction().
    add(R.id.fragment_container, bf).commit();
    bf.setText("hello world"); // call here
like image 43
ρяσѕρєя K Avatar answered Nov 07 '22 03:11

ρяσѕρєя K


The problem is FragmentTransaction is async by default

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment_container, BlankFragment.newInstance);
ft.disallowBackStack();
ft.commitNowAllowingStateLoss();

Then you still can't get the Fragment yet, you have to get it from the FragmentTransaction

BlankFragment bf = (BlankFragment) getSupportFragmentManager().getFragmentById(R.id.fragment_container);
bf.setText("hello world");

This article helped me to understand this problem better

like image 1
cutiko Avatar answered Nov 07 '22 03:11

cutiko