0

I have one problem here. I need to change background of Layout which is in navigationView. Here is what I do

protected void onCreate(Bundle savedInstanceState) {

    try {
        ConnectivityManager con = (ConnectivityManager) getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo net = con.getActiveNetworkInfo();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        themeInfo = getSharedPreferences("THEMECONFIG",0);
        themeSetting = themeInfo.getString("theme","Základná");



        if (net != null && net.isConnected()) {
            if (isOnline()) {
                //setContentView(R.id.nav_header_logo);
                navHeaderLogo = (LinearLayout)findViewById(R.id.nav_header_logo);

                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
                drawer.setDrawerListener(toggle);
                toggle.syncState();


                navigationView.setNavigationItemSelectedListener(this);


            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Hups, niečo je zle :(")
                        .setMessage("Internet nie je dostupný")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();

            }

        } else {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Hups, niečo je zle :(")
                    .setMessage("Chýba pripojenie k internetu. Zapnite prosím dáta alebo Wi-Fi a spustite aplikáciu znova.")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }


    } catch (Exception e) {
        Log.e("chyba", e.getMessage());
    }

    swt = (SwitchCompat)findViewById(R.id.lokalizationSwitch);

    if(ContextCompat.checkSelfPermission(Settings_activity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED)
    {
        swt.setChecked(false);
        checker = false;
    }
    else
    {
        swt.setChecked(true);
        checker = true;
    }
    swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            MainActivity.checker = false;
            MainActivity2.checker2 = false;
            MainActivity3.checker3 = false;


            if(isChecked == true)
            {
                if (ContextCompat.checkSelfPermission(Settings_activity.this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

                    ActivityCompat.requestPermissions(Settings_activity.this,
                            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                            permissionCheck);
                    checker = true;


                    }
            }
            else if (isChecked == false && checker == true)
            {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);

                checker = false;
            }

        }

    });
    this.isCreated = true;
    themes = (Spinner) findViewById(R.id.comboBoxTheme);
    themeSetting = themeInfo.getString("theme","Základná");
    if(themeSetting.equals("Základná"))
    {
        themes.setSelection(0);
        setTheme(R.style.AppTheme);
        checker2 = false;
    }
    if(themeSetting.equals("Matrix"))
    {
        themes.setSelection(1);
        setTheme(R.style.AppThemeMatrixDivider);
        checker2 = false;
    }
    if(themeSetting.equals("Gamers"))
    {
        themes.setSelection(2);
        setTheme(R.style.AppThemeGamersDivider);
        checker2 = false;
    }
    themes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            int index = arg0.getSelectedItemPosition();
            if(!themeSetting.equals(themes.getItemAtPosition(index).toString()))
            {
                changeTheme(themes.getItemAtPosition(index).toString());
                checker2 = false;

            }



        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            checker2 = true;
        }

    });

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    Button sett = (Button)findViewById(R.id.button_settings);
    TextView text = (TextView)findViewById(R.id.textview);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("setItemIconTintList",R.drawable.menu_text_color_normal) ));
    navigationView.setItemTextColor(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("setItemTextColor",R.drawable.menu_text_color_normal) ));
    navigationView.setBackgroundDrawable(ContextCompat.getDrawable(Settings_activity.this, themeInfo.getInt("setBackgroundDrawable",R.drawable.border_top_bottom_normal) ));
    sett.setTextColor(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("settSetTextColor",R.color.colorWhite) ));
    text.setTextColor(ContextCompat.getColorStateList(Settings_activity.this, themeInfo.getInt("textSetTextColor",R.color.colorDefault) ));
    toolbar.setBackground(ContextCompat.getDrawable(Settings_activity.this, themeInfo.getInt("toolbarSetBackground",R.color.colorPrimary) ));
    toolbar.getNavigationIcon().setColorFilter(getResources().getColor(themeInfo.getInt("toolbarGetNavigationIcon()",R.color.colorWhite)), PorterDuff.Mode.SRC_ATOP);



}

When I use LinearLayout navHeaderLogo=(LinearLayout)this.findViewById(R.id.nav_header_logo); it just showes me an error like this

    E/chyba: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.lodka.lodkanadejeapp, PID: 12231
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lodka.lodkanadejeapp/com.example.lodka.lodkanadejeapp.Settings_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:156)
                      at android.app.ActivityThread.main(ActivityThread.java:6531)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
                      at com.example.lodka.lodkanadejeapp.Settings_activity.onCreate(Settings_activity.java:259)
                      at android.app.Activity.performCreate(Activity.java:6910)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864) 
                      at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
                      at android.os.Handler.dispatchMessage(Handler.java:105) 
                      at android.os.Looper.loop(Looper.java:156) 
                      at android.app.ActivityThread.main(ActivityThread.java:6531) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)

 

I know that this is out of view because the background changing should be made elsewhere. But do you guys have some solution for me? Because I tried almost everything and nothing really worked.

Here is XML which I am using

    <?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"
    android:id="@+id/nav_header"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/border_top_bottom_normal"
    android:gravity="bottom"
    android:orientation="vertical"

    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:weightSum="1">


    <LinearLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/nav_header_logo"
        android:layout_width="match_parent"
        android:layout_height="@dimen/nav_header_height"
        android:background="@drawable/border_top_bottom_normal_logo"
        android:gravity="bottom"
        android:orientation="vertical"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:weightSum="1">
    <ImageView

        android:id="@+id/logoImg"
        android:background="@android:color/transparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="25pt"
        android:src="@mipmap/lodkauvodbp"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:srcCompat="@android:drawable/sym_def_app_icon"/>


    </LinearLayout>

</LinearLayout>

Here is activity_settings.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:weightSum="1"
        android:divider="?android:dividerHorizontal"
        android:showDividers="middle"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textview1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="50px"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Nastavenia"
            android:textSize="25dp"
            android:typeface="serif" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="left">
                <TextView
                    android:id="@+id/labelswitch"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Povolenie pre lokalizáciu"
                    android:textSize="15dp"
                    android:typeface="serif"
                    android:gravity="left"
                    android:textColor="#000000"/>
                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="right">
                    <android.support.v7.widget.SwitchCompat
                        android:id="@+id/lokalizationSwitch"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:checked="true" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="left">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Výber farebnej témy"
                    android:textSize="15dp"
                    android:typeface="serif"
                    android:textColor="#000000"/>
                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:gravity="right">

                    <Spinner
                        android:id="@+id/comboBoxTheme"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textAlignment="textEnd"
                        android:layout_gravity="end"
                        android:drawSelectorOnTop="true"
                        android:entries="@array/theme_array" />

                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>


    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        app:itemTextColor="@drawable/menu_text_color_normal"
        app:itemIconTint="@drawable/menu_text_color_normal"
        android:background="@drawable/border_top_bottom_normal">


    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible" />



    </android.support.design.widget.NavigationView>

</android.supp

ort.v4.widget.DrawerLayout>

PS: I know that problem like this is already solved here, but this is specific problem for me

UPDATE: I updated onCreate method UPDATE 2: Updated error message UPDATE 3: Added activity_settings.xml

Tibor
  • 33
  • 6
  • Try to remove `this` – Cagri Yalcin Mar 23 '18 at 13:51
  • and are you sure about `isOnline()` method returns `true` ? – Cagri Yalcin Mar 23 '18 at 13:53
  • 1
    Your code doesn't match that stack trace. There is no `SwitchCompat` or `setChecked()` call in the snippet you've posted. – Mike M. Mar 23 '18 at 13:53
  • Please post the full source code of your `Settings_activity` – Ernest Zamelczyk Mar 23 '18 at 13:56
  • Here is an explanation of [super.onCreate](https://stackoverflow.com/a/14671985/1331156). Best regards. – gusioo Mar 23 '18 at 13:59
  • @CagriYalcin this didn't help me and yes I am sure. This app works perfectly. I just need to change background, but I need to initialize linear layout, which is now impossible for me :/, – Tibor Mar 23 '18 at 20:46
  • @MikeM I updated the code :) – Tibor Mar 23 '18 at 20:47
  • @ErnestZamelczyk updated code above :) – Tibor Mar 23 '18 at 20:47
  • The problem is with this line `navigationView.setBackgroundDrawable(ContextCompat.getDrawable(Settings_activity.this, themeInfo.getInt("setBackgroundDrawable",R.drawable.border_top_bottom_normal) ));`. Your navigationView is null so it's probably some problem in a activity_settings.xml. Please post full source code of your activity layout. The one you posted is for drawer header. – Ernest Zamelczyk Mar 25 '18 at 10:23
  • @ErnestZamelczyk I added activity_settings.xml :) – Tibor Mar 25 '18 at 13:47

2 Answers2

1

Move your:

 setContentView(R.layout.activity_settings);

to right after the super call, like this:

 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_settings);

If you're not online (isOnline() is false) your view will never get inflated and this will cause problems down the line when you try to find something by id.

Levi Moreira
  • 11,917
  • 4
  • 32
  • 46
  • sorry but this didn't help me :) – Tibor Mar 24 '18 at 15:02
  • could you try move the code `super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings);` to before the try statement? – Levi Moreira Mar 24 '18 at 15:39
  • I tried this but didn't help :/... app even crashed :/ – Tibor Mar 24 '18 at 19:35
  • Where is nav_view in your xml? If your activity_settings doesn't seem to have it, therefore you won't find it, therefore it will return null and your app will fail when you try to call any method on that view. – Levi Moreira Mar 25 '18 at 11:28
0

Ok i found a solution. I just had to do something like that

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    View header = navigationView.getHeaderView(0);
    LinearLayout linear = (LinearLayout) header.findViewById(R.id.nav_header_logo);
    linear.setBackground(ContextCompat.getDrawable(this, R.drawable.border_top_bottom_matrix_logo));

This works perfectly and nav_header_logo is not null anymore

Tibor
  • 33
  • 6