Android ActionBar always null - android

I have an activity with a navigation drawer that flicks between fragments. Nothing special.
However what I want is the action bar to appear at the top of the activity. The issue is that I keep getting a nullpointerexception for the Actionbar.
I've tried answers from the following pages:
getActionBar returns null
getActionBar() returns Null (AppCompat-v7 21)
None of these have worked so I thought I'd submit my own question with my own code.
MainActivity.java
package com.jampez.smalltalk;
import com.jampez.smalltalk.fragments.HomeFragment;
import com.jampez.smalltalk.fragments.MessageFragment;
import com.jampez.smalltalk.fragments.PreferencesFragment;
import com.jampez.smalltalk.fragments.SettingsFragment;
import com.jampez.smalltalk.helper.SessionManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String[] items;
int selectedPosition;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setTitle("");
// Session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
items = getResources().getStringArray(R.array.menus);
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
/* Creating an ArrayAdapter to add items to mDrawerList */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, items);
mDrawerList.setAdapter(adapter);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open) {
/* Called when drawer is closed */
public void onDrawerClosed(View view) {
//Put your code here
}
/* Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
//Put your code here
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedPosition = position;
/* Replace fragment content */
displayView(position);
/* Closing the drawer */
mDrawerLayout.closeDrawer(mDrawerList);
}
});
/* Setting default fragment */
selectedPosition = 0;
displayView(0);
}
private void displayView(int position) {
// update the main content by replacing fragments
android.app.Fragment fragment = null;
Log.i("position", position+"");
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new MessageFragment();
break;
case 2:
fragment = new PreferencesFragment();
break;
case 3:
fragment = new SettingsFragment();
break;
case 4:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
case 5:
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
//setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#android:style/Theme.WithActionBar" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer list-->
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
HomeFragment.java
package com.jampez.smalltalk.fragments;
import com.jampez.smalltalk.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
//getActivity().getActionBar().setTitle(R.string.home);
return rootView;
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e5e5e5"
android:orientation="vertical" >
<TextView
android:id="#+id/home_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="start|center_vertical"
android:text="#string/home"/>
</LinearLayout>
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jampez.smalltalk"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:name=".app.AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name=".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>
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
</application>
styles.xml
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:actionBarStyle">#style/MyActionBar</item>
<item name="android:actionOverflowButtonStyle">#style/MyActionButtonOverflow</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#color/white</item>
</style>
<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.ActionButton.Overflow">
<item name="android:color">#color/white</item>
</style>
<style name="MyActionBar" parent="#android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">#25a0da</item>
</style>
Logcat Output
11-08 19:17:38.618: E/AndroidRuntime(6347): FATAL EXCEPTION: main
11-08 19:17:38.618: E/AndroidRuntime(6347): Process: com.jampez.smalltalk, PID: 6347
11-08 19:17:38.618: E/AndroidRuntime(6347): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jampez.smalltalk/com.jampez.smalltalk.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.ActivityThread.access$900(ActivityThread.java:172)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.os.Handler.dispatchMessage(Handler.java:102)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.os.Looper.loop(Looper.java:145)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.ActivityThread.main(ActivityThread.java:5832)
11-08 19:17:38.618: E/AndroidRuntime(6347): at java.lang.reflect.Method.invoke(Native Method)
11-08 19:17:38.618: E/AndroidRuntime(6347): at java.lang.reflect.Method.invoke(Method.java:372)
11-08 19:17:38.618: E/AndroidRuntime(6347): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
11-08 19:17:38.618: E/AndroidRuntime(6347): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
11-08 19:17:38.618: E/AndroidRuntime(6347): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
11-08 19:17:38.618: E/AndroidRuntime(6347): at com.jampez.smalltalk.MainActivity.onCreate(MainActivity.java:37)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.Activity.performCreate(Activity.java:6221)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
11-08 19:17:38.618: E/AndroidRuntime(6347): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
11-08 19:17:38.618: E/AndroidRuntime(6347): ... 10 more

*First of all include this dependency in your gradle file
compile 'com.android.support:appcompat-v7:22.2.0'
*You should extend your activity to AppCompactActivity and start using toolbar instead of ActionBar.
*This is how you use Toolbar in your MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
*this is how to add toolbar in your activity_main.xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
*your theme should look something like this styles.xml
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
</style>
<style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
make sure you add this style name in your manifest for your application.
*It will be better if you use v4.app.Fragment rather than using Fragment.
*this is how you should set title from your Fragment class
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.home);
Refer this clear Tutorial which will surely help you setting up material Navigation drawer.
If you want to quickly start off without much pain then you can try integrating this third party library.

If you are not getting a ActionBar at all, like visualy, try to rewrite your Activity so you are able to use AppCompatActivity. This thread suggests to use ActionbarActivity instead of FragmentActivity. Since ActionbarActivity is deprecated, AppCompatActivity should work just fine.
For the Nullpointer issue:
Always be consistent with what you are using. If you decide to use AppCompat, make sure you are extending AppCompatActivity. Double check all imports - you might be using the normal Fragment instead of the AppCompat version.
Check your styles and make sure to use AppCompat parents instead of holo ones. That also includes your Actionbar. Instead of Widget.Holo.Light.ActionBaruse parent="#style/Widget.AppCompat.Light.ActionBar".
Always call getSupportActionBarinstead of getActionBar(). Sometimes it might even be neccessary to cast the Activity you are getting with getActivity() in a Fragment to AppCompatActivity to be sure you are getting the right one: ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("");.

Ok so none of the answers posted have given me much success. I have however managed to get the action bar displayed but with somewhat limited functionality.
The first thing I did was to replace the appcompat_v7 library with android-support-v7-appcompat. Doing this allows me to call the action bar using getActionBar().
The limitation come with trying to control aspects of the action bar. I can set the title and icon fine but if I try to use ActionBarDrawerToggle I get a NullPointerException. I also noticed that tapping on the action bar does nothing when normally it opens the drawer.

Did you try to put getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
in your onCreate() method? It helped me once. Also try changing theme to Holo

Related

This Activity already has an action bar supplied by the window

I have a problem with my Navigation Drawer.
my project First run by splash page and Then show Navigation Drawer.
When I compile my application the following error messages :
AndroidRuntime: FATAL EXCEPTION: main
Process: ir.mosayebtorabi.sapp, PID: 4793
java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.mosayebtorabi.sapp/com.loridic.ir.loridic.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:201)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:129)
at com.loridic.ir.loridic.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
at android.app.ActivityThread.access$800(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5293) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
activity_splash_screen.xml Contains:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
tools:context="com.loridic.ir.loridic.SplashScreen">
<ImageView
android:id="#+id/image"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/lorvajeh"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.4"
android:contentDescription="#string/lorem_ipsum" />
<TextView
android:id="#+id/welcomeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome_screen"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/image"
app:layout_constraintVertical_bias="0.2"
android:textSize="22sp"
android:textColor="#color/colorWhite"
android:textStyle="bold"/>
activity_splash_screen class Contains:
package com.loridic.ir.loridic;
import android.app.Activity;`
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
public class SplashScreen extends AppCompatActivity {
Handler handler;
public static Activity fa;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
fa = this;
ImageView iv = findViewById(R.id.image);
TextView tv = findViewById(R.id.welcomeText);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.splashtransition);
iv.startAnimation(animation);
tv.startAnimation(animation);
Splashregister();
}
public void Splashregister() {
handler = new Handler();
{
handler.postDelayed(new Runnable() {
#Override
public void run() {
fa.finish();
startActivity(new Intent(SplashScreen.this, MainActivity.class));
}
}, 4000);
}
}
}
styles.xml Contains:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
MainActivity class Contains:
package com.loridic.ir.loridic;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FrameLayout frameLayout;
FragmentManager fragmentManager=getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
frameLayout=(FrameLayout)findViewById(R.id.frmlayoutview);
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 navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.SentWord) {
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.frmlayoutview,new FragmentClassAddWord());
ft.commit();
} else if (id == R.id.Target) {
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.frmlayoutview,new FragmentClassAbout());
ft.commit();
} else if (id == R.id.PersonalInformation) {
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.frmlayoutview,new FragmentClassRegistername());
ft.commit();
} else if (id == R.id.Share) {
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.frmlayoutview,new FragmentClassShare());
ft.commit();
} else if (id == R.id.About) {
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.frmlayoutview,new FragmentClassMaker());
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
MainActivity xml Contains:
<?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">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
AndroidManifest.xml Contains:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loridic.ir.loridic">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreen"
android:label="LoreVajeh"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activityaddword" />
<activity android:name=".Activityregistername" />
<activity android:name=".Activityabout" />
<activity android:name=".Activitymaker" />
<activity android:name=".Activityshareapp" />
<activity android:name=".MainActivity"></activity>
</application>
</manifest>
As you are supplying a toolbar in your MainActivity you need to turn the default one off in the AndroidManifest.xml file
e.g.
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />

Error with Navigation Drawer

Hello I am a young Belgian developer and follow currently a tutorial on YouTube to create a Drawer Navigation but I get errors when launching the emulator due.
This is the Tutorial.
Here are the errors :
02-10 11:31:12.432 2297-2297/com.example.flori.mylordring E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flori.mylordring, PID: 2297
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.flori.mylordring/com.example.flori.mylordring.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference
at com.example.flori.mylordring.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
And Main code :
package com.example.flori.mylordring;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static ImageButton imgView;
private int test;
int [] images = {R.drawable.im1,R.drawable.im2,R.drawable.im3,R.drawable.im4,R.drawable.im5,R.drawable.im6,R.drawable.im7};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Rolololo", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void image(View view){
imgView=(ImageButton)findViewById(R.id.imageButton);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
test++;
test = test % images.length;
imgView.setImageResource(images[test]);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Activity code (I have 2 different activities and this is the content_main, i also have activity_main) :
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawerLayout"
android:background="#e2656262"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.flori.mylordring.MainActivity"
tools:showIn="#layout/activity_main">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentholder">
</FrameLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/navlist"
android:background="#dedede"
android:layout_gravity="start"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ImageButton
android:onClick="image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:src="#drawable/im1"
android:background="#android:color/transparent"
android:layout_above="#+id/textView"
android:layout_centerHorizontal="true" />
</android.support.v4.widget.DrawerLayout>
the Manifest code :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flori.mylordring">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
**</manifest>
and my2 styles.xml :
this is my style.xml :**
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
Style.xml(V21) :
<resources>>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
</style>
</resources>
In this part of code:
ActionBar actionBar = getSupportActionBar(); //will return null
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);//why set it after you call getSupportActionBar?
As you can see above you are getting the actionbar before set the toolbar as your actionbar, which will return null.
you need to switch those so you will get the reference from your toolbar.
Or in another words, you could use getSupportActionBar():
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // First initialize the Toolbar
setSupportActionBar(toolbar); // Set as SupportActionBar
getSupportActionBar().setDisplayShowHomeEnabled(true); // do your stuffs
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
And the second problem is:
app:layout_behavior="#string/appbar_scrolling_view_behavior"
Which you set it for Drawer and it shouldn't be there, check this link:
https://github.com/codepath/android_guides/wiki/Handling-Scrolls-with-CoordinatorLayout#expanding-and-collapsing-toolbars
Add an app:layout_behavior to a RecyclerView or any other View capable
of nested scrolling such as NestedScrollView. The support library
contains a special string resource
#string/appbar_scrolling_view_behavior that maps to
AppBarLayout.ScrollingViewBehavior, which is used to notify the
AppBarLayout when scroll events occur on this particular view

Error with my toolbar while creating tabs

I am using an androidhive tutorial to design my tabs since the tabhost has been deprecated. It is my first time using the new features. However, I keep getting this error:
java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
I have read solutions to similar problems here and the proposed solution is to set some properties in the theme however everything looks good in my styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item> <!--change here-->
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="button_text" >
<item name="android:layout_width" >fill_parent</item>
<item name="android:layout_height" >wrap_content</item>
<item name="android:textColor" >#ffffff</item>
<item name="android:gravity" >center</item>
<item name="android:layout_margin" >3dp</item>
<item name="android:textSize" >30sp</item>
<item name="android:textStyle" >bold</item>
<item name="android:shadowColor" >#000000</item>
<item name="android:shadowDx" >1</item>
<item name="android:shadowDy" >1</item>
<item name="android:shadowRadius" >2</item>
</style>
</resources>
Below is a section of my manifest file:
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity android:name=".MaintenanceActivity" >
</activity>
<activity android:name=".ServicingActivity">
</activity>
Here is the activity_maintenance.xml
<android.support.design.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="com.application.sweetiean.stlmaintenance.MaintenanceActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
and finally, here is the MaintenanceActivity.java
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MaintenanceActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintenance);
init();
}
public void init(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OverviewFragment(), "Overview");
adapter.addFragment(new BaseDataFragment(), "Base Data");
adapter.addFragment(new TaskFragment(), "Task");
adapter.addFragment(new ImageSignFragment(), "Images/Sign");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I cannot see what is going on wrong in my code because I am not receiving the same error when i start up the main activity so I believe it has something to do with the tab implementation. I would be grateful if anyone can help me out. Thank you.
Error about wrong theming: you are trying to set Actionbar, while it already exists. So:
<activity android:name=".MaintenanceActivity" >
</activity>
You set no theme for this activity. Just add:
android:theme="#style/AppTheme.NoActionBar"
Like you do to main activity. GL
You need to change your AppTheme style from:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to :
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
to discard the already-existing actionBar.

Binary inflater :Error inflating class android.support.design.widget.NavigationView

I followed a tutorial of new component NavigationView in Support Design Library and can't get through this error message
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.encore/com.encore.NavViewActivity}: android.view.InflateException: Binary XML file line #27: Error inflating class android.support.design.widget.NavigationView
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
<item name="android:colorPrimary">#color/PrimaryColor</item>
<item name="android:colorPrimaryDark">#color/PrimaryDarkColor</item>
<item name="windowActionModeOverlay">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
layout file
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/lib/com.encore.NavViewActivity"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
/>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer"
/>
java file
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class NavViewActivity extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.inbox:
Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.starred:
Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.sent_mail:
Toast.makeText(getApplicationContext(),"Send Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.drafts:
Toast.makeText(getApplicationContext(),"Drafts Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.allmail:
Toast.makeText(getApplicationContext(),"All Mail Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.trash:
Toast.makeText(getApplicationContext(),"Trash Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.spam:
Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
}
I also encountered the same problem,Error exactly,Later I found out wrong here:menu->item->android:icon="#drawable/ic_menu_camera",thisic_menu_camera header has vector only used in v21 or higher,so in system 5.0 or less useing can get the problems,than you can copy the following code in values folder and Named "drawables".code:<resources xmlns:android="http://schemas.android.com/apk/res/android">
<item name="ic_menu_camera" type="drawable">#android:drawable/ic_menu_camera</item>
<item name="ic_menu_gallery" type="drawable">#android:drawable/ic_menu_gallery</item>
<item name="ic_menu_slideshow" type="drawable">#android:drawable/ic_menu_slideshow</item>
<item name="ic_menu_manage" type="drawable">#android:drawable/ic_menu_manage</item>
<item name="ic_menu_share" type="drawable">#android:drawable/ic_menu_share</item>
<item name="ic_menu_send" type="drawable">#android:drawable/ic_menu_send</item>
</resources>
Try replacing android:layout_gravity="start"with android:layout_gravity="right" inside NavigationView layout.
check your navigation view by removing one of these and check your code is working or not
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer"
if your logcat says cause by resourcenotfoundexception with your above error. issue may be with a icon file/resource file in drawers. if it coming from menu/drawer try changing icons and add icons to drawer folder and to drawer-v21. hope this helps

Navigation drawer (menudrawer) Android 5 (lollipop) style

I'm using menudrawer library in my project (this one: https://github.com/SimonVT/android-menudrawer).
I'm updating my app to be compatible with API21 (Android 5 Lollipop) and Material Design. When you use this library with API21 menudrawer icon looks bad.
I want to achieve transition you can see in the new Play Store (new menudrawer icon transition to arrow).
What's the best way to do that? Is it possible with this library? The only solution I'm thinking at the moment is custom drawable. But maybe I can use native drawable some way?
OK. I spent few hours with new API and I think that the best for me will be rewriting my drawer from lib to native DrawerLayout.
But maybe this will be useful for someone with similar problem. I've created test project with DrawerLayout (Android Studio -> New Project with menudrawer).
And then I saw the same problem. Wrong icon. If you want to see fancy animation and good icon for Android 5.0 make sure you are using:
import android.support.**v7**.app.ActionBarDrawerToggle;
Take note on v7. By default Fragment class has v4 import and then you won't see good icon.
Another thing. After changing to v7 you need to fix ActionBarDrawerToggle function to new constructor. And that's it. You'll see new drawer icon.
First, make sure you update to latest SDK. Create new Project in Android Studio, then add appcompat-v7.21.0.+ and appcompat-v4.21.0.+ libraries in your buid.gradle as gradle dependency.
compile 'com.android.support:appcompat-v7:21.0.2'
compile 'com.android.support:support-v4:21.0.2'
Add primaryColor and primarycolorDark in your color.xml file.
<resources>
<color name="primaryColor">#2196F3</color>
<color name="primaryColorDark">#0D47A1</color>
</resources>
Add drawer open/close string value in your strings.xml file.
<resources>
<string name="app_name">Lollipop Drawer</string>
<string name="action_settings">Settings</string>
<string name="drawer_open">open</string>
<string name="drawer_close">close</string>
</resources>
Your activity_my.xml layout file looks like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:id="#+id/drawerLayout"
android:layout_height="match_parent">
<!-- activity view -->
<RelativeLayout
android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:textColor="#000"
android:text="Activity Content"
android:layout_height="wrap_content" />
</RelativeLayout>
<!-- navigation drawer -->
<RelativeLayout
android:layout_gravity="left|start"
android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#eee"
android:background="#fff"
android:dividerHeight="1dp" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Your toolbar.xml layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
Your MyActivity.java looks like this:
Here your activity must extends ActionBarActivity and set your toolbar as support actionbar.
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MyActivity extends ActionBarActivity {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ListView leftDrawerList;
private ArrayAdapter<String> navigationDrawerAdapter;
private String[] leftSliderData = {"Home", "Android", "Sitemap", "About", "Contact Me"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
nitView();
if (toolbar != null) {
toolbar.setTitle("Navigation Drawer");
setSupportActionBar(toolbar);
}
initDrawer();
}
private void nitView() {
leftDrawerList = (ListView) findViewById(R.id.left_drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationDrawerAdapter=new ArrayAdapter<String>( MyActivity.this, android.R.layout.simple_list_item_1, leftSliderData);
leftDrawerList.setAdapter(navigationDrawerAdapter);
}
private void initDrawer() {
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Create style.xml file in values-21 folder for android lollipop
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="myAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="android:statusBarColor">#color/primaryColorDark</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#android:color/black</item>
</style>
</resources>
Create your style.xml file in values folder for older versions then android lollipop
<resources>
<style name="myAppTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#android:color/black</item>
</style>
</resources>
Your AndroidManifest.xml is looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nkdroid.com.lollipopdrawer" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/myAppTheme" >
<activity
android:name=".MyActivity"
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>
For reference only:
you can download complete source code from here : click here
Check out the new lollipop components released in May 2015 by Android team.
Design Support Library
Blog on Design Support Library

Categories

Resources