I get this nullPointerException on runtime:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method \'void android.app.ActionB
Put assert getActionBar () != null;
after mActionBar = getActionBar();
This problem might be caused by your theme. Check it again, and make sure that it parent with Theme.AppCompat.Light.DarkActionBar
.
<style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">true</item>
...
</style>
If your activity extends AppCompatActivity
or ActionBarActivity
, call getSupportActionBar()
.
This is clearly not the problem of OP, but other people may find it useful: for me the solution was to call setContentView(R.layout.activity_main) before the configuration of actionbar.
In my case, I forgot to init my Toolbar, so, before using getSupportActionBar, I had to do this:
appbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(appbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_nav_menu);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
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();
}
};
If you check this answer in 2019 like me , the problem is about your android manifest:
<application
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
Check the documentation here:
https://developer.android.com/training/appbar/setting-up.html
You also take in mind the previous answer from TetianaDev:
Instead of:
public class MainActivity extends Activity {
use:
public class MainActivity extends AppCompatActivity {
and instead of:
getActionBar().setTitle(mTitles);
use:
getSupportActionBar().setTitle(mTitles);
This works for me.