I am using a template navigation drawer that was provided by android studio. I am very new to android development so i'm wondering if i'm missing something simple here. I want to start a new activity by clicking on an item in my navigation menu I followed several tutorials on how to do this but i keep getting this error in my logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
Here is the code I tried to start a new activity:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
}
else if (id == R.id.nav_gallery) {
Intent intent = new Intent(MainActivity.this, second_activity.class);
startActivity(intent);
}
else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I referred to my second activity in my manifest file like this:
<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>
<activity android:name=".second_activity">
<intent-filter>
<action android:name="com.example.bsmyth.sidemenu.second_activity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Here is the drawer layout:
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="Adfeed"
android:checked="true"/>
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="Post" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="Notification" />
<item
android:id="#+id/nav_manage"
android:icon="#drawable/ic_menu_send"
android:title="Messages" />
</group>
Here is the second activity:
package com.example.bsmyth.sidemenu;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
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;
public class second_activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(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 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.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is second_activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
And here are the error messages in logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.bsmyth.sidemenu.second_activity.onCreate(second_activity.java:30)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Your second activity layout has only a DrawerLayout and one TextView it does not have the views that you are calling in onCreate method.
Try running it again after removing this views from your onCreate:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
add this:
android:id="#+id/drawer_layout"
to your DrawerLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Use a little common sense on these, you are using findViewById for drawer_layout, toolbar as well as nav_view and other extras too.
But there is nothing in second_activity layout except one TextView even that is without any id. Then how can these codes work ?
Create these elements like shown in new android project in android studio then follow the same pattern and see how the next layout is included there.
Your will get multiple NullPointerException in your code. You only copied the code of MainActivity.java to second_activity.java but not in the layout file from activity_main to second_activity.
You can create your second activity in project explorer and selecting the activity you want from the template. It is the easiest way and also very good way. After that you can simply call the second activity from first activity like you are doing now
You are doing many things wrong in second activity code....
In layout XML..you don't give any id for drawer layout which you are using (drawer_layout).
So Add this...
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your in the second activity"
android:textSize="20sp"/>
</android.support.v4.widget.DrawerLayout>
Also create this view toolbar and nav_view in this XML file like you have create Textview in second_activity XML .
And create Drawer object only once with same drwaer id(drawer_layout).
Like...
//declare this globally(means out of any method)
DrawerLayout drawer;
and then initialize this in onCreate method...
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
and at last remove this line DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); from onBackPressed() and onNavigationItemSelected method.
Hope this will help you...
Related
This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
Closed 4 years ago.
I created the Activity with the Wizard.
I deleted what I am not interested in, for example, the floating action button.
Created my custom items in the activity_main_drawer.xml
The wizard created the onNavigationItemSelected function (see code below) and I added my code so it quits the activity and goes back to the Login Screen.
So I don't know why, I see nothing interesting in the logcat so this is a logical problem. I am a newbie and Navigation View scares me a lot... Let me know if I missed anything you need.
package com.skrefi.googleplaycopy;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
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.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//Don't know what this is
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//Don't know what this is either
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//In case I need it for the admin activity >> the 3 dots pop down thingy <<
#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.
MakeToast("SOMETHING");
switch (item.getItemId()){
case R.id.action_settings:
MakeToast("Settings button clicked");
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void MakeToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
Edit:
So it may be confusing if I set the visibility to gone and I get use the layout I want right in this layout file because I get the screen without the toolbar, this is what I want. AND I want to keep that as well for the admin part, to check later in if the user is me, and if so, I get a new item in the drawer called Admin Activity which simply set the thingy visibility to visible so i get the admin screen.
Here is what you (#) asked for:
<?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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--This is for a potential admin screen-->
<include
android:id="#+id/include_toolbar_with_threedots_settings"
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<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.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is for test"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.DrawerLayout>
You're calling finish() before actually starting your activity while you should call it after starting your login activity. The following code will start Login activity and close the Main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch(item.getItemId()){
case R.id.item_signout:
firebaseAuth.getInstance().signOut();
MakeToast("Signed out!");
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
break;
}
//DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
I am a complete newbie in android development. At the moment I am trying to replicate an app I saw on where it is possible to convert multiple images (jpeg, png, jpg) into a single pdf file. I have tried to do the most I can with debugging. But I don't understand why there are still this NullPointer Exception.
Oh and by the way please pardon me if I have some mistakes in placing proper tags or such in my question this is my first question thank you.
Here's my code for the ConvertToPDFConverter.java
package com.example.lenovo_thinkpad.mobilelectureboard;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.os.Bundle;
import android.view.MenuItem;
import android.view.View;
public class ConvertToPDFConverter extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
android.support.v7.app.ActionBar bar;
CustomActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert_to_pdfconverter);
bar = this.getSupportActionBar();
assert bar != null;
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setDisplayShowTitleEnabled(false);
drawer = findViewById(R.id.drawer_layout);
drawer.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
try {
toggle = new CustomActionBarDrawerToggle(this, drawer);
} catch (RuntimeException e) {
e.printStackTrace();
}
drawer.addDrawerListener(toggle);
// Set navigation drawer
// Set com.example.lenovo_thinkpad.mobilelectureboard.Home fragment
Fragment fragment = new Home();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
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 onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
switch (id) {
case R.id.nav_camera:
fragment = new Home();
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
break;
case R.id.nav_gallery:
fragment = new ViewFiles();
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
}
#Override
public void onDrawerClosed(View view) {
bar.setTitle(getString(R.string.navigation_drawer_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
bar.setTitle(getString(R.string.navigation_drawer_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
}
and for the layout activity_convert_to_pdfconverter.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">
<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"
android:fitsSystemWindows="true"
tools:context=".ConvertToPDFConverter">
<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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/mb_white"
android:id="#+id/content"/>
</android.support.design.widget.CoordinatorLayout>
<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>
Here's the stacktrace
02-13 15:12:17.976 1548-1548/com.example.lenovo_thinkpad.mobilelectureboard E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lenovo_thinkpad.mobilelectureboard, PID: 1548
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo_thinkpad.mobilelectureboard/com.example.lenovo_thinkpad.mobilelectureboard.ConvertToPDFConverter}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.lenovo_thinkpad.mobilelectureboard.ConvertToPDFConverter.onCreate(ConvertToPDFConverter.java:34)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<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_picker">
<activity
android:name=".MainActivity"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WhiteBoardActivity" />
<activity android:name=".ConvertToPDFConverter" />
</application>
Since you are extending the AppCompatActivity, try to get the actionbar via 'getSupportActionbar()'.
I know there are many equal to the problems but none of the many who have read is equal to mine or has worked for me for help , so it is going to require your help.
I'm working on an application with a NavigationDrawer , I need to make an image work for me on and off the bluetooth cell .
I made another code separately with an " empty activity" and if I worked, but in the navigariondrawe that is where I need it to work , but it does not work , I 've tried many things , but I hope you can help me .
FATAL EXCEPTION: main
Process: com.example.lab02pc19.myapplication2, PID: 5146
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab02pc19.myapplication2/com.example.lab02pc19.myapplication2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.lab02pc19.myapplication2.MainActivity.setImagenBluetooth(MainActivity.java:69)
at com.example.lab02pc19.myapplication2.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6245)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab02pc19.myapplication2">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<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>
package com.example.lab02pc19.myapplication2;
import android.bluetooth.BluetoothAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
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.ImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentBlue.OnFragmentInteractionListener {
ImageView miimagen;
BluetoothAdapter adaptador_bluetooth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
miimagen= (ImageView)findViewById(R.id.ivw);
adaptador_bluetooth= BluetoothAdapter.getDefaultAdapter();
if(adaptador_bluetooth==null)
{
miimagen.setVisibility(View.GONE);
}
else
{
setImagenBluetooth(adaptador_bluetooth.isEnabled());
}
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);
}
public void clickImagen(View view)
{
switch (view.getId())
{
case R.id.ivw:
setEstadoBluetooth();
break;
}
}
public void miimagen()
{
setEstadoBluetooth();
}
public void setImagenBluetooth(boolean valor)
{
if(valor)miimagen.setImageResource(R.drawable.ic_action_bluetooth);
}
public void setEstadoBluetooth()
{
if(adaptador_bluetooth.isEnabled())
{
setImagenBluetooth(false);
adaptador_bluetooth.disable();
}
else
{
setImagenBluetooth(true);
adaptador_bluetooth.enable();
}
}
#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.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
boolean FragmenTransaction= false;
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = new FragmentBlue();
FragmenTransaction= true;
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if(FragmenTransaction)
{
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,fragment).commit();
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
<FrameLayout 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"
tools:context="com.example.lab02pc19.myapplication2.FragmentBlue">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivw"
android:layout_gravity="left|top"
android:background="#drawable/ic_action_bluetooth"
android:clickable="true"
android:onClick="clickImagen"
android:contentDescription="#string/imagen" />
</FrameLayout>
As I think (it is not enough info), you want to create a fragment in the activity and make some actions with ImageView further. But you didn't create the fragment and try to find ImageView by id in other layout - thus, the image view didn't exist here, next you try to call function of the null object and finally have a NPE and crash. You need to read tutorial about fragment in Android: https://developer.android.com/training/basics/fragments/index.html
You are trying to access the image view of the fragment in your activity class which is not possible that's why giving null point exception. What you can do it that you can setImage in the image view in you fragment java class in onActivityCreated override method after setting the contentView.
If you want to set the image from the activity only then you can create the public method in the fragment and call the method from the activity.
I am using the android Navigation drawer template and fragments to display different views.
as the normal there is a MainActivity, activity_main.xml and content_main.xml generated automatically.
I have created two java classes; MusicFragment and MainFragment and of course the layout files which I have content inside.
When I run the app the activity_main is the default layout launched which I have welcome content displaying, I am using the Navigation drawer to navigate to my MusicFragment and MainFragment, this code I using to replace the current view in the onNavigationItemSelected method is;
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
these both work fine with replacing each other although I have a big problem, when I select the nav drawer and hit the camera option it shows the fragment view but does not replace the content from activity_main it shows the fragment content on top of the content_main and doesn't replace it.
This is my MainActivity:
package com.justmikey.justmik;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.internal.widget.ButtonBarLayout;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
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.Button;
import android.widget.TextView;
import JustMikey.Fragments.MainFragment;
import JustMikey.Fragments.MusicFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//create a media player object called mp
MediaPlayer mp;
//declare my buttons play, pause and stop
Button play, pause,stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the textView scrollMain to scrollable
TextView tv = (TextView) findViewById(R.id.scrollMain);
tv.setMovementMethod(new ScrollingMovementMethod());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(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 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.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camara) {
fm.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
} else if (id == R.id.nav_gallery) {
fm.beginTransaction().replace(R.id.content_frame, new MusicFragment()).commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior" tools:showIn="#layout/app_bar_main"
tools:context=".MainActivity"
android:background="#dbe4eb">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/content_frame">
<ImageView
android:layout_width="355dp"
android:layout_height="wrap_content"
android:src="#drawable/jmmain"
android:id="#+id/imageView2"
android:layout_gravity="center_horizontal|top"
android:layout_alignRight="#+id/content_frame"
android:layout_alignEnd="#+id/content_frame" />
<TextView
android:layout_width="fill_parent"
android:layout_height="274dp"
android:text="hello hello hello hello hello hello hello hello"
android:id="#+id/scrollMain"
android:layout_gravity="center_horizontal|bottom"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="28dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#ffffff"
android:padding="10dp"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center">
</ScrollView>
</FrameLayout>
</RelativeLayout>
FragmentTransactions only handle Fragments. They will not replace/remove anything not in a Fragment. Since those Views contained in the content_frame FrameLayout are only needed at startup, we can simply remove them upon the first FragmentTransaction.
To do this, we'll create a member boolean flag, isStartup, initialized to true. In the onNavigationItemSelected() method, we'll check the flag, and if it's true, remove the Views and change it to false.
Declare and initialize the boolean outside of any method:
private boolean isStartup = true;
Then do the check and removal in the onNavigationItemSelected() method.
public boolean onNavigationItemSelected(MenuItem item) {
android.app.FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if(isStartup) {
((FrameLayout) findViewById(R.id.content_frame)).removeAllViews();
isStartup = false;
}
if (id == R.id.nav_camara) {
...
}
I had the same problem.
I could not solve my problem with the said solutions. But i found two solutions to solve it!
1- You can present the content of the main page into an other view group. and hide it in onNavigationItemSelected, in the right place:
content_main.xml:
<RelativeLayout 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="#dbe4eb"
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:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/my_linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/content_frame"
android:layout_alignRight="#+id/content_frame"
android:layout_gravity="center_horizontal|top"
android:src="#drawable/jmmain" />
<TextView
android:id="#+id/scrollMain"
android:layout_width="fill_parent"
android:layout_height="274dp"
android:layout_alignBottom="#+id/scrollView"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="28dp"
android:background="#ffffff"
android:padding="10dp"
android:text="hello hello hello hello hello hello hello hello" />
<ScrollView
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center"></ScrollView>
</LinearLayout>
</RelativeLayout>
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
findViewById(R.id.my_linearLayout).setVisibility(View.VISIBLE);
fragmentManager.popBackStack("fragment", POP_BACK_STACK_INCLUSIVE);
} else if (id == R.id.one) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
findViewById(R.id.my_linearLayout).setVisibility(View.GONE);
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
2- The second way is to consider a fragment for the contents of the main page as well. and then in the onNavigationItemSelected method, we treat it Like the rest of the fragments:
onNavigationItemSelected method in MainActivity.java:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.main) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.one) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new OneFragment()).addToBackStack("fragment").commit();
} else if (id == R.id.tow) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).addToBackStack("fragment").commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
note: To display the contents of the main page when opening the program enter the following code in onCreate() in MainActivity:
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).addToBackStack("fragment").commit();
I am trying to use the android navigation drawer with the action bar of AppCompatActivity. But when I implement the action bar the icon to open the navigation drawer is missing in it.
This is what I want to be displayed
This is a screenshot of my current action bar
You can see my code below.
This is my activity_main.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"
android:id="#+id/main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"/>
<!--app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view" />-->
</android.support.v4.widget.DrawerLayout>
This is my action_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
This is my MainActivity
package com.blog.waiyanhein.llks.llks;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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);
}
}
Why is the icon to open the navigation drawer missing using my code?
You didn't implement the NavigationDrawer in your Activityi guess.i've had the same problem and that fixed with the following code.
In your Activity:
private DrawerLayout drawerLayout;
In your onCreate:
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.home:
drawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
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) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
Strings.xml:
<string name="openDrawer">Navigation</string>
<string name="closeDrawer">Close Navigation</string>
Then it should work.
Try this code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
You may need to include:
actionBarDrawerToggle.syncState();
The answer here may help:
Appcompatv7 - v21 Navigation drawer not showing hamburger icon