Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]
Asked Answered
E

26

121

I have a code module which implements viewpager with navigation drawer, however, when I run the code I get the following error

01-26 09:20:02.958: D/AndroidRuntime(18779): Shutting down VM
01-26 09:20:02.959: E/AndroidRuntime(18779): FATAL EXCEPTION: main
01-26 09:20:02.959: E/AndroidRuntime(18779): Process: com.example.tabwithslidingdrawer, PID: 18779
01-26 09:20:02.959: E/AndroidRuntime(18779): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tabwithslidingdrawer/com.example.tabwithslidingdrawer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.ActivityThread.access$800(ActivityThread.java:148)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.os.Looper.loop(Looper.java:135)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.ActivityThread.main(ActivityThread.java:5312)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at java.lang.reflect.Method.invoke(Native Method)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at java.lang.reflect.Method.invoke(Method.java:372)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
01-26 09:20:02.959: E/AndroidRuntime(18779): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
01-26 09:20:02.959: E/AndroidRuntime(18779):    at com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.Activity.performCreate(Activity.java:5953)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
01-26 09:20:02.959: E/AndroidRuntime(18779):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
01-26 09:20:02.959: E/AndroidRuntime(18779):    ... 10 more
09:20:02.959: E/AndroidRuntime(18779): Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null
object reference 01-26 09:20:02.959: E/AndroidRuntime(18779):     at
com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95)

points to this line

// enabling action bar app icon and behaving it as a toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

entire code http://pastebin.com/u1K72fr7

My manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tabwithslidingdrawer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Tabwithpager" >
        <activity
            android:name="com.example.tabwithslidingdrawer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

android:theme="@style/Theme.Tabwithpager"

code http://pastebin.com/EFQLzRej

================================================================== EDIT/UPDATE:

What I learnt from this

Whenever such an error occurs

1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.

2. Check if your activity type which is extended falls under the compat category

example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based

if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()

3. Check the theme applied to the activity in question in the manifest file

example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work

but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()

Euphemia answered 26/1, 2015 at 4:4 Comment(10)
di you try getSupportActionbar()?Astrodome
i am using getSupportActionbar already in my codeEuphemia
Did you use App compat theme? You should post your Manifest with your activity declaration here for further help.Astrodome
you should look at your code again. I can get supportActionBar (not null) with your theme. Did you replace all getActionBar with getSupportActionBar? 1 more thing, you should update your new error log.Astrodome
i searched my workspace , there are no instances of getActionBar , ive uploaded the whole project for reference drive.google.com/file/d/0BwRMp8dK9LMLem5WZjZaYkxZeWs/…Euphemia
I looked at your code. Actually, you still use getActionBar() in your MainActivity... Check it and change to getSupportActionBar.Astrodome
i think when i went to search i replaced all getSupportActionbar with getActionBar :(Euphemia
You answer is perfect. working 100%Norbert
@Pir Fahim Shah Which answer? You commented the question...Emmons
@TheincredibleJan I've added a collated answer at the end of the question.Euphemia
A
163

Your code is throwing on com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95):

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

The problem is pretty simple- your Activity is inheriting from the new android.support.v7.app.ActionBarActivity. You should be using a call to getSupportActionBar() instead of getActionBar().

If you look above around line 65 of your code you'll see that you're already doing that:

        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        // TODO: Remove the redundant calls to getSupportActionBar()
        //       and use variable actionBar instead
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

And then lower down around line 87 it looks like you figured out the same:

        getSupportActionBar().setTitle(
                        Html.fromHtml("<font color=\"black\">" + mTitle + " - "
                                        + menutitles[0] + "</font>"));
        // getActionBar().setTitle(mTitle +menutitles[0]);

Notice how you commented out getActionBar().

Ambages answered 12/2, 2015 at 1:9 Comment(2)
Just a note: android.support.v7.app.ActionBarActivity has been deprecated in favor of android.support.v7.app.AppCompatActivity. But the issue is the same.Ambages
Inside a fragment, see herePinball
D
36

If anybody wants to use android.app.ActionBar and android.app.Activity you should change the app theme in styles.xml, for example:

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

The problem is you could be using an AppCompat theme.

On the other hand, if you want to use android.support.v7.app.ActionBar and you extend your activity with AppCompatActivity then you must use an AppCompat theme to avoid this issue, for example:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Hope this helps.

Dyslogistic answered 3/9, 2015 at 9:14 Comment(3)
You can also extend from AppCompatActivity instead of Activity, as in this answer.Giltedged
Sure @Keith, if you want to use an AppCompat theme you must use an AppCompatActivity otherwise you will have the same incompatibility problem.Dyslogistic
@Dyslogistic Thanks!Artemas
Q
19

when you extend appcompatActivity then use

this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and when you extend ActionBar then use

this.getActionBar().setDisplayHomeAsUpEnabled(true);

dont forget to call this function in oncreate after initializing the toolbar/actionbar

Quadruplet answered 18/2, 2016 at 19:3 Comment(2)
I don't know how to call this function, can you please tell me the way to this function - FazalLarissa
extend your class with respectively classes according to your use. This is the code for java not kotlin and added few years ago i am not sure that if android have changed itQuadruplet
Y
13

Try to check here

res >> values >> styles.xml

make sure that there no code like this

<item name="windowActionBar">false</item>

if there are code like that, you can disable for a while, or erase it

Yasui answered 24/6, 2016 at 2:57 Comment(2)
thank you for reminding!! :D I also left in <item name="windowNoTitle">true</item>, which had to be removed.Sennet
For me, what worked was remove android:theme="@style/AppTheme.NoActionBar" from <avticity> tag on AndroidManifest.xmlTegan
K
12

I think what you want to do is cast getActivity(). For example:

((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

This is what you need to do with the new support libraries. AppCompatActivity has replaced ActionBarActivity.

Khano answered 2/6, 2015 at 18:30 Comment(0)
G
6

In my case is because of styles.xml set the wrong parent theme, i.e. NoActionBar theme of course getSupportActionbar() is null:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

Changed it to something else fixed it:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
Gulley answered 25/1, 2017 at 18:2 Comment(0)
B
5

When use AppCompatActivity must call

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

Before getSupportActionBar()

public class PageActivity extends AppCompatActivity {
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        this.getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    }
}
Beccafico answered 6/8, 2017 at 13:18 Comment(0)
C
2

The Up Button is usually activated for Low-level Activities. In your manifest I only see the MainActivity. I don't think it makes sense to activate the up button for the main activity. Create an activity, then in the manifest add the parentActivityName attribute. Then activate the up button on the activity's onCreate method.
This should help.
https://developer.android.com/training/appbar/up-action.html

Crustal answered 22/9, 2015 at 21:38 Comment(0)
I
2

If you are using android.app.ActionBar and android.app.Activity you should change the app theme in application tag:

< application
     android:theme="@android:style/Theme.Holo.Light">
Imagination answered 29/5, 2016 at 4:48 Comment(0)
S
2

If you encounter this error

"java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle (java.lang.CharSequence)' on a null object reference. "

Just use

setSupportActionBar (toolbar). 
Sump answered 16/12, 2019 at 19:23 Comment(0)
P
2

I am a new to Android App development. I faced this error and spend almost 5 hours trying to fix it. Finally, i found out the following was the root cause for this issue and if anyone to face this issue again in the future, please give this a read.

I was trying to create a Home Activitiy with a Video Background, for which i had to change the parent theme from the default setting of Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.Light.NoActionBar. This worked fine for the Home Activity, but when i set a new button with a onclicklistener to navigate to another Activity, where i had set a custom text to the Action Bar, this error is thrown.

So, what i ended up doing was to create two themes and assigned them to the activities as follows.

Theme.AppCompat.Light.DarkActionBar - for Activities with Action Bar (default)
Theme.AppCompat.Light.NoActionBar - for Activities without Action Bar 

I have made the following changes to make fix the error.

  1. Defining the themes in styles.xml

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    
    <style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    
  2. Associating the Activities to their Respective Themes in AndroidManifest.xml

    <activity android:name=".Payment"
        android:theme="@style/DefaultTheme"/>
    
    <activity android:name=".WelcomeHome"
        android:theme="@style/AppTheme.NoActionBar">
    
Plough answered 21/3, 2020 at 20:18 Comment(0)
M
1

For those still having this issue, my issue was resolved in the AndroidManifest.xml file. Where it says <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">, you need to remove NoActionBar, making it <activity android:name=".MainActivity" android:theme="@style/AppTheme">, because with NoActionBar set the app doesnt know whether or not it wants an action bar when you call one up inside of MainActivity.java

Mongolism answered 2/6, 2016 at 14:32 Comment(0)
T
1

in this line in your activity:

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

use this:

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

* is your activity

Tridentine answered 2/8, 2016 at 22:22 Comment(0)
M
1

In my case I had the same error but my mistake was that I didn't declare my Toolbar.

So, before I use getSupportActionBar I had to find my toolbar and set the actionBar

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

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_nav_menu);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Mikimikihisa answered 20/8, 2016 at 3:12 Comment(0)
M
1

I know that this question is something old. But this can help many who present this problem.

To solve this problem, check if there is a point of nullity. Then apply the corresponding configuration:

if(getSupportActionBar() != null){
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
 getSupportActionBar().setHomeButtonEnabled(true);
}
Martyrize answered 7/4, 2018 at 21:6 Comment(0)
H
1

The best solution do this in your Oncreate method

 ActionBar actionBar = getSupportActionBar();

        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

followed by a new class

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if(id == android.R.id.home){
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

Hax answered 13/7, 2019 at 14:1 Comment(1)
Although this code snippet may answer the question, including an explanation of why and how it helps solve the problem improves the quality and longevity of your answer. See How do I write a good answer?Starlike
P
1

Try this hope it will work, my code is works fine

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

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("");
Piccadilly answered 20/11, 2019 at 18:26 Comment(0)
W
1

it solves:

Change the theme in the AndroidManifest.xml from:

  android:theme="@style/AppTheme.NoActionBar"

to

android:theme="@style/AppTheme"

These themes are in Styles.xml.

Change it, that's it!

Wool answered 4/1, 2023 at 2:18 Comment(0)
O
0

For anyone else who has a BaseActivity, and a child that extends from it, make sure the super.onCreate() is called first before you do anything. The old Activity would work if you called super.onCreate() afterwards.

Child extends Activity - could call super after you did stuff

@Override
protected void onCreate(Bundle savedInstanceState)
{
    getActionBar().setDisplayHomeAsUpEnabled(true);
    super.onCreate(savedInstanceState);

Child extends AppCompatActivity - ya gotta call super first

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState); //do this first
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Officinal answered 1/10, 2015 at 15:24 Comment(0)
C
0

I got the same error once, I created a template for a default toolbar( toolbar.xml) and then in another view I created a collapsable toolbar.

I required to add the collapsable toolbar to a view that show some information of the user(like whatsapp), but the method findViewById was referencing the default toolbar(id toolbar), not the collapsable one( id toolbar as well) yes, I wrote the same id to both toolbar, so when I tried to access the activity the app crashed showing me the error.

I fixed the error by changing the id of the collapsable toolbar to id:col_toolbar and the error gone away and my app worked perfectly

Cultivable answered 2/2, 2018 at 1:50 Comment(0)
P
0

You should try this one. I think it will work.

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

    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout.setDrawerShadow(R.drawable.rectagle_with_black_outer,
            GravityCompat.START);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            toolbar, R.string.navigation_drawer_close,
            R.string.navigation_drawer_close) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu();
        }
    };
Pharmacology answered 12/6, 2019 at 11:46 Comment(0)
H
0

Please add after Toolbar

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
Holocrine answered 3/3, 2020 at 15:45 Comment(0)
P
0

I am not using AppCompat but am using android.app.Activity and android.widget.Toolbar. I too got an error similar to above. Jotting down below the things that I did to resolve the issue incase anyone else has a similar problem:

i. For me the themes did not have any effect. I continued to use Theme.AppCompat.Light.DarkActionBar

ii. Ensure that your toolbar layout has the Toolbar entry:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/design_default_color_primary"
        android:titleTextColor="@color/white"
        android:theme="@style/Theme.Material3.Dark"
        />

</LinearLayout>

iii. In your activity's layout file, ensure that the above is included:

<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="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ChildActivity">

    <include layout="@layout/child_toolbar"
        android:id="@+id/child_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

</LinearLayout>

iv. Set the ActionBar in the onCreate function of your activity as follows:

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setActionBar(toolbar);
Possessed answered 31/1, 2022 at 15:17 Comment(0)
N
-1

Whenever such an error occurs. Try to check Following Things

  1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.

  2. Check if your activity type which is extended falls under the compat category

example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based

if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()

  1. Check the theme applied to the activity in question in the manifest file

example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work

but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()

Norbert answered 11/1, 2020 at 20:19 Comment(0)
R
-1

if u have creat a new toolbar then apply check that u have apply the method setSupportActionBar(); it will defenetly help you

Richierichlad answered 25/6, 2020 at 11:30 Comment(0)
G
-3

Try doing this:

                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setHomeButtonEnabled(true);
                actionBar = getSupportActionBar();
                actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

Instead of this:

actionBar = getSupportActionBar();
                actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setHomeButtonEnabled(true);
Germ answered 26/1, 2015 at 4:16 Comment(3)
Why to call getSupportActionBar() if you already has its result in actionBar variable? Both variants are bad.Nachison
You change getSupportActionBar(); to actionBar = getSupportActionBar(); It's the same!!!! Shake a leg!!!!!Dudeen
It does not make any differenceDyslogistic

© 2022 - 2024 — McMap. All rights reserved.