简体   繁体   中英

Android studio null object reference error while changing component visibility

I'm making an app that displays the same menus for different users, each menu being a fragment, but depending on the user certain things are visible and others aren't.

However, when I try to set a component's visibility as GONE I get a null pointer exception error, I'm still testing so I'm only using a textView on the fragment xml.

I've already tried initializing both the TextView and the FragmentMenuEncomenda , the class of the fragment I'm using, objects, both inside the if clause before the onCreate() method, and after the setContentView() , like the tabLayout and viewPager .

The if clause was only to make sure the user type was correct and the code in question is as follows:

public class PaginaInicialCliente extends AppCompatActivity {

    private SharedPreferences sharedpreferences;

    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        tabLayout = findViewById(R.id.tabLayoutCliente);
        viewPager = findViewById(R.id.viewPagerCliente);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        //fragments a adicionar
        adapter.addFragment(new FragmentMenuEncomendas(), "Encomendas");
        adapter.addFragment(new FragmentMenuOpcoes(), "Opções");

        //inicializar o tab layout
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);

        if (sharedpreferences.getInt("tipo",0)==3) {
            Log.d("USER_DEBUG","Cliente");
            FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
            
            //THE ERROR IS HERE
            fragmentMenuEncomendas.getActivity().findViewById(R.id.textViewEncomendas).setVisibility(View.GONE);
        }

    }
}

The FragmentMenuEncomenda class:

public class FragmentMenuEncomendas extends Fragment {

    View v;

    public FragmentMenuEncomendas(){
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.encomendas_fragment, container, false);
        return v;
    }
}

The xml file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textViewEncomendas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

All the answers I've searched didn't work, I don't know if it's because I'm trying to change the visibility inside the on create method.

Because view is not created when you call the function.

public class FragmentMenuEmpresas extends Fragment {

    View v;
    View textView;
    boolean isTextViewShow = false;
    boolean isViewCreated = false;

    public FragmentMenuEmpresas() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.empresas_fragment, container, false);
        textView = v.findViewById(R.id.textViewEncomendas);
        return v;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (isTextViewShow) {

            textView.setVisibility(View.VISIBLE);
        } else {

            textView.setVisibility(View.GONE);
        }

        isViewCreated = true;
    }

    void setIsTextViewShow() {

        if (isViewCreated) {

            textView.setVisibility(View.VISIBLE);
        } else {

            isTextViewShow = true;
        }
    }

    void setIsTextViewGone() {
        
        if (isViewCreated) {

            textView.setVisibility(View.GONE);
        } else {

            isTextViewShow = false;
        }
    }
}

then you can call the setIsTextViewShow or setIsTextViewGone anytime you want

 FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
                       
 fragmentMenuEncomendas.setIsTextViewShow();//show
 fragmentMenuEncomendas.setIsTextViewGone();//gone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM