How to fix "NullPointerException" in viewmodel.setText? : <p>I'm trying to pass the user information from MainActivity to one of the fragments in my NavigationHeader and i keep getting a NullPointerException everytime i try to setText in the Fragment.</p>

<p>I tried using the Bundle and Interface approach before trying ViewModel. Also getActivity() warns me that it's null.</p>

<pre><code>public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;


    //NavHeader
    private TextView header_name, header_email;

    //SessionManager
    SessionManager sessionManager;

    //maps
    private static final String TAG = "MainActivity";
    private static final int ERROR_DIALOG_REQUEST = 9001;

    private static final String FINELOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSELOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;

    private Boolean mLocationPermissionsGranted = false;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;

    private static final float DEFAULT_ZOOM = 15f;

    private FusedLocationProviderClient mFusedLocationProviderClient;

    private GoogleMap mMap;


    String pontopartida, pontochegada;

    private EditText ponto_partidaInput, ponto_chegadaInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //GET USER DATA
        sessionManager = new SessionManager(this);
        sessionManager.checkLogin();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);

        header_name = (TextView) headerView.findViewById(R.id.header_name);
        header_email = (TextView) headerView.findViewById(R.id.header_email);



        HashMap&lt;String, String&gt; user = sessionManager.getUserDetail();
        String mName =  user.get(sessionManager.NAME);
        String mEmail = user.get(sessionManager.EMAIL);

        header_name.setText(mName);
        header_email.setText(mEmail);



        //Navigation Drawer
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);
        navigationView.setNavigationItemSelectedListener(this);


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_myaccount:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MyAccountFragment()).commit();
                break;
            case R.id.nav_settings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SettingsFragment()).commit();
                break;
            case R.id.nav_logout:
                sessionManager.logout();
                break;
            case R.id.nav_share:
                Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }else{
            super.onBackPressed();
        }
    }
}


</code></pre>

<p>and MyAccountFragment</p>

<pre><code>
public class MyAccountFragment extends Fragment {

    private SharedViewModel viewModel;
    private EditText account_name;
    private EditText account_email;

    protected FragmentActivity mActivity;


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

        View view = inflater.inflate(R.layout.fragment_myaccount, container, false);



        account_name = (EditText) view.findViewById(R.id.name_accountfrag);
        account_email = (EditText) view.findViewById(R.id.email_accountfrag);
        viewModel.setText(account_name.getText().toString());


        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), new Observer&lt;String&gt;() {
            @Override
            public void onChanged(@Nullable String s) {
                account_name.setText(s);
            }
        });
    }
}

</code></pre>

<p>Also here is my error log</p>

<pre><code>
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tiago.teleperformance, PID: 9236
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.tiago.teleperformance.SharedViewModel.setText(java.lang.String)' on a null object reference
        at com.example.tiago.teleperformance.MyAccountFragment.onCreateView(MyAccountFragment.java:42)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

</code></pre>

<p>I was expecting it to update the information in the Fragment with the same Name and Email in the MainActivity as soon as i opened it. Instead it crashes. Can anyone help me?</p>
