NullPointerException在Navigation Drawer中启动新Activity时

时间:2016-04-01 09:55:24

标签: android android-activity navigation-drawer start-activity

我正在使用android studio提供的模板导航抽屉。我对android开发很新,所以我想知道我是否在这里错过了一些简单的东西。我想通过单击导航菜单中的项目开始一项新活动我按照几个教程了解如何执行此操作但我在logcat中不断收到此错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsmyth.sidemenu/com.example.bsmyth.sidemenu.second_activity}: java.lang.NullPointerException

以下是我尝试开始新活动的代码:

@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;
}
}

我在清单文件中提到了我的第二个活动,如下所示:          

<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>

这是抽屉布局:

<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>

这是第二项活动:

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;
    }
}

这是second_activity布局:

<?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>

以下是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) 

5 个答案:

答案 0 :(得分:1)

您的第二个活动布局只有一个DrawerLayout和一个TextView,它没有您在onCreate方法中调用的视图。 从onCreate中删除此视图后尝试再次运行它:

   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);
   NavigationView navigationView = (NavigationView)    findViewById(R.id.nav_view);
   navigationView.setNavigationItemSelectedListener(this);

答案 1 :(得分:0)

添加:

android:id="@+id/drawer_layout"

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>

答案 2 :(得分:0)

对这些使用一点常识,您使用findViewById drawer_layouttoolbar以及nav_view和其他附加内容。

但除second_activity之外,TextView布局中没有任何内容,即使没有任何id也是如此。那么这些代码怎么能运作呢?

创建这些元素,如android studio中新的android项目所示,然后按照相同的模式,看看下一个布局是如何包含在那里的。

答案 3 :(得分:0)

您的代码中会有多个NullPointerException。您只将MainActivity.java的代码复制到second_activity.java,但未将其从activity_main复制到second_activity的布局文件中。

您可以在项目资源管理器中创建第二个活动,并从模板中选择所需的活动。这是最简单的方式,也是非常好的方式。之后,您可以简单地从第一个活动中调用第二个活动,就像您现在正在做的那样

答案 4 :(得分:0)

你在第二个活动代码中做了很多错事.... 在布局XML中..您不能为您正在使用的抽屉布局(drawer_layout)提供任何ID。 所以添加这个......

<?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>

在此XML文件中创建此视图工具栏 nav_view ,就像在second_activity XML中创建Textview一样。

使用相同的drwaer id(drawer_layout)创建一次Drawer对象。 像...

//declare this globally(means out of any method)
DrawerLayout drawer; 

然后在onCreate方法中初始化...

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

最后从onBackPressed()和onNavigationItemSelected方法中删除此行DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

希望这会对你有帮助......