Kaki In
Kaki In

Reputation: 94

Why does findViewById() returns "null"?

I have an important issue with java
I have this code :

package fr.christian.lbcde;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;

import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import fr.christian.lbcde.ui.main.PageViewModel;
import fr.christian.lbcde.ui.main.SectionsPagerAdapter;

public class MainActivity extends AppCompatActivity {

    PageViewModel pageViewModel;
    View activity_main, tab_create, tab_connect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        FloatingActionButton fab = findViewById(R.id.fab);

        tab_connect = findViewById(R.id.tab_connect);
        tab_create = findViewById(R.id.tab_create);
        System.out.print("Result of tab_connect : ");
        System.out.print(findViewById(R.id.tab_connect));
        System.out.print(" ");
        System.out.println(tab_connect==null);
        System.out.print("Result of tab_create : ");
        System.out.print(findViewById(R.id.tab_create));
        System.out.print(" ");
        System.out.println(tab_create==null);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addNew();
            }
        });
//        hideAll();
//        tab_connect.setVisibility(View.VISIBLE);
        pageViewModel.addTabListener(new PageViewModel.tabChangeListener() {
            @Override
            public void onChangeTab(View view, int tab) {
                switch (tab) {
                    case 1:
                        hideAll();
                        tab_connect.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        hideAll();
                        tab_create.setVisibility(View.VISIBLE);
                        break;
                    default:
                        new Toast(getApplicationContext())
                                .makeText(getApplicationContext(), "Rien a afficher pour cet onglet", Toast.LENGTH_SHORT)
                                .show();
                }
            }
        });
    }

    public void addNew() {
        new Toast(getApplicationContext())
                .makeText(getApplicationContext(), "Cette option n'est pas encore disponible", Toast.LENGTH_SHORT)
                .show();
    }

    public void hideAll() {
        View[] views = {
                tab_create,
                tab_connect
        };
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.INVISIBLE);
        }
        ;
    }

}

and four files for my layouts :

activity main.xml :

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

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.LeBonCoinDeLÉvangile.AppBarOverlay">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            app:tabSelectedTextColor="?attr/colorPrimaryVariant"/>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:background="?attr/colorPrimary"
        app:srcCompat="@android:drawable/ic_menu_info_details" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>


fragment_main.xml
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.PlaceholderFragment">

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginBottom="@dimen/activity_vertical_margin">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="horizontal">
            <include layout="@layout/login_main"/>
            <include layout="@layout/create_main"/>
        </LinearLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

create_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tab_create"
    android:orientation="vertical"
    android:layout_marginStart="@dimen/activity_horizontal_margin"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    android:layout_marginEnd="@dimen/activity_horizontal_margin"
    android:layout_marginBottom="@dimen/activity_vertical_margin"
    android:visibility="invisible">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TAB_CREATE"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BONJOUR LES ÉLËPHANTS"/>
</LinearLayout>

and login_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tab_connect"
    android:orientation="vertical"
    android:layout_marginStart="@dimen/activity_horizontal_margin"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    android:layout_marginEnd="@dimen/activity_horizontal_margin"
    android:layout_marginBottom="@dimen/activity_vertical_margin">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TAB_CONNECT"/>
    <TextView
        style="@style/h2textStyle"
        android:text="@string/titleConnect_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/loginConnect_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />
</LinearLayout>



The problem is that at the lines :
System.out.print(findViewById(R.id.tab_connect));


and

System.out.print(findViewById(R.id.tab_create));

I have this result (for the both) :

null

So I can't remove the error "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference" in hideAll(), tab_create.setVisibility(View.VISIBLE), etc... because when I initialize my layouts, they are initialized with a null object (and not my layouts).
I add some lines like

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TAB_CREATE"/>

in my file to see if those tabs are really those I see on my screen and its appear that I really see them (when I cancel the lines with the layouts visibility).
Thanks for your help!

Upvotes: 0

Views: 612

Answers (1)

laalto
laalto

Reputation: 152917

Your tab_connect etc. are included in fragment_main layout and not in activity_main layout that is inflated when you call findViewById() for those ids. The code you posted does not show where you're using fragment_main but what is certain is that it is not in your activity's view hierarchy at the time when you try to look up those views.

Either move the findViewById() calls and whatever you're doing with the views to the fragment, or move the views from the fragment to your main activity.

Upvotes: 1

Related Questions