新活动,同样的菜单

时间:2016-01-14 13:35:31

标签: java android android-activity android-studio menu

我已经构建了一个新活动(.Notitie),试图将相同的菜单作为主要活动(.MainActivity)。但它给出了一个致命的例外::

 01-14 08:24:05.756 12945-12945/nl.verpleegkundigzakboek.www.verpleegkundigzakboek E/AndroidRuntime: FATAL     EXCEPTION: main
Process: nl.verpleegkundigzakboek.www.verpleegkundigzakboek, PID: 12945
 java.lang.RuntimeException: Unable to start activity  ComponentInfo{nl.verpleegkundigzakboek.www.verpleegkundigzakboek/nl.verpleegkundigzakboek.www.verpleegkundigzakboek.Notities}: 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 nl.verpleegkundigzakboek.www.verpleegkundigzakboek.Notities.onCreate(Notities.java:64)
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)

它说它的原因是:java.lang.NullPointerException at nl.verpleegkundigzakboek.www.verpleegkundigzakboek.Notities.onCreate(Notities.java:64)

所以我猜问题就在于这段代码:

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) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    getLoaderManager().initLoader(0, null, this);

来自我的Notities活动:

package nl.verpleegkundigzakboek.www.verpleegkundigzakboek;

import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class Notities extends AppCompatActivity
        implements LoaderManager.LoaderCallbacks<Cursor>, NavigationView.OnNavigationItemSelectedListener {

NavigationView navigationView = null;
Toolbar toolbar = null;

private static final int EDITOR_REQUEST_CODE = 1001;
private CursorAdapter cursorAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notities);

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

    cursorAdapter = new NotesCursorAdapter(this, null, 0);

    ListView list = (ListView) findViewById(android.R.id.list);
    list.setAdapter(cursorAdapter);

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(Notities.this, EditorActivity.class);
            Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
            intent.putExtra(NotesProvider.CONTENT_ITEM_TYPE, uri);
            startActivityForResult(intent, EDITOR_REQUEST_CODE);
        }
    });

    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) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    getLoaderManager().initLoader(0, null, this);

}

private void insertNote(String noteText) {
    ContentValues values = new ContentValues();
    values.put(DBOpenhelper.NOTE_TEXT, noteText);
    Uri noteUri = getContentResolver().insert(NotesProvider.CONTENT_URI,
            values);
    Log.d("Notities", "Inserted note " + noteUri.getLastPathSegment());
}

@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.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
        case R.id.action_create_sample:
            insertSampleData();
            break;
        case R.id.action_delete_all:
            deleteAllNotes();
            break;
    }

    return super.onOptionsItemSelected(item);
}

private void deleteAllNotes() {

    DialogInterface.OnClickListener dialogClickListener =
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int button) {
                    if (button == DialogInterface.BUTTON_POSITIVE) {
                        //Insert Data management code here
                        getContentResolver().delete(
                                NotesProvider.CONTENT_URI, null, null
                        );
                        restartLoader();

                        Toast.makeText(Notities.this,
                                getString(R.string.all_deleted),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(getString(R.string.are_you_sure))
            .setPositiveButton(getString(android.R.string.yes), dialogClickListener)
            .setNegativeButton(getString(android.R.string.no), dialogClickListener)
            .show();
}

private void insertSampleData() {
    insertNote("Simple note");
    insertNote("Multi-line\nnote");
    insertNote("Very long note with a lot of text that exceeds the width of the screen");
    restartLoader();
}

private void restartLoader() {
    getLoaderManager().restartLoader(0, null, this);
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, NotesProvider.CONTENT_URI,
            null, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    cursorAdapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    cursorAdapter.swapCursor(null);
}

public void openEditorForNewNote(View view) {
    Intent intent = new Intent(this, EditorActivity.class);
    startActivityForResult(intent, EDITOR_REQUEST_CODE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == EDITOR_REQUEST_CODE && resultCode == RESULT_OK) {
        restartLoader();
    }
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        //set the fragment initially
        MainFragment fragment = new MainFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
        //handle the camera action
    } else if (id == R.id.nav_gallery) {
        Zakkaartjes fragment = new Zakkaartjes();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_slideshow) {
        Rekenen fragment = new Rekenen();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_manage) {
        Intent intent = new Intent(this, Notities.class);
        startActivity(intent);
        finish();

    } else if (id == R.id.nav_share) {
        Protocollen fragment = new Protocollen();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();


    } else if (id == R.id.nav_send) {
        Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
                "mailto","info@verpleegkundigzakboek.nl", null));
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email van verpleegkundig zakboek app");
        startActivity(Intent.createChooser(emailIntent, "Verzend e-mail"));

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

添加了我的activity_notities:

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Notities">

<ListView
    android:id="@+id/android:list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<at.markushi.ui.CircleButton
    android:layout_width="64dp"
    android:layout_height="64dp"
    app:cb_color="@color/primary"
    app:cb_pressedRingWidth="8dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_action_add"
    android:onClick="openEditorForNewNote"/>

<include
    layout="@layout/app_bar_notities"
    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" />

<!--<Button-->
<!--android:id="@+id/button"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentBottom="true"-->
<!--android:layout_alignParentEnd="true"-->
<!--android:layout_alignParentRight="true"-->
<!--android:onClick="openEditorForNewNote"-->
<!--android:text="New note" />-->

希望有人可以给我一个提示?!

grtzzz

1 个答案:

答案 0 :(得分:0)

在您的activity_notities.xml文件中,您似乎错过了您尝试在以下行中引用的抽屉布局( drawer_layout ):

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

此行期望您的导航抽屉布局为android:id="@+id/drawer_layout"。因为在xml文件中没有这样的布局drawer为空。

以下是从Android Developers site获取的drawerLayout的示例:

<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">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#111"/>
</android.support.v4.widget.DrawerLayout>