启动新活动时出现错误 Android

5

我是一名新手Android开发者,在创建新的Activity时遇到了一些问题。我想在点击一个Button时启动一个新的Activity,但应用程序崩溃了。以下是控制台和日志记录中显示的内容:

日志记录

03-11 00:21:08.639: D/AndroidRuntime(336): Shutting down VM
03-11 00:21:08.649: W/dalvikvm(336): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-11 00:21:08.659: E/AndroidRuntime(336): FATAL EXCEPTION: main
03-11 00:21:08.659: E/AndroidRuntime(336): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.src.vicnote/com.src.vicnote.MainActivity}: java.lang.NullPointerException
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.os.Looper.loop(Looper.java:123)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-11 00:21:08.659: E/AndroidRuntime(336):  at java.lang.reflect.Method.invokeNative(Native Method)
03-11 00:21:08.659: E/AndroidRuntime(336):  at java.lang.reflect.Method.invoke(Method.java:507)
03-11 00:21:08.659: E/AndroidRuntime(336):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-11 00:21:08.659: E/AndroidRuntime(336):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-11 00:21:08.659: E/AndroidRuntime(336):  at dalvik.system.NativeStart.main(Native Method)
03-11 00:21:08.659: E/AndroidRuntime(336): Caused by: java.lang.NullPointerException
03-11 00:21:08.659: E/AndroidRuntime(336):  at com.src.vicnote.MainActivity.onCreate(MainActivity.java:26)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-11 00:21:08.659: E/AndroidRuntime(336):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-11 00:21:08.659: E/AndroidRuntime(336):  ... 11 more
03-11 00:21:38.579: D/AndroidRuntime(365): Shutting down VM
03-11 00:21:38.579: W/dalvikvm(365): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-11 00:21:38.599: E/AndroidRuntime(365): FATAL EXCEPTION: main
03-11 00:21:38.599: E/AndroidRuntime(365): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.src.vicnote/com.src.vicnote.MainActivity}: java.lang.NullPointerException
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.os.Looper.loop(Looper.java:123)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-11 00:21:38.599: E/AndroidRuntime(365):  at java.lang.reflect.Method.invokeNative(Native Method)
03-11 00:21:38.599: E/AndroidRuntime(365):  at java.lang.reflect.Method.invoke(Method.java:507)
03-11 00:21:38.599: E/AndroidRuntime(365):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-11 00:21:38.599: E/AndroidRuntime(365):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-11 00:21:38.599: E/AndroidRuntime(365):  at dalvik.system.NativeStart.main(Native Method)
03-11 00:21:38.599: E/AndroidRuntime(365): Caused by: java.lang.NullPointerException
03-11 00:21:38.599: E/AndroidRuntime(365):  at com.src.vicnote.MainActivity.onCreate(MainActivity.java:26)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-11 00:21:38.599: E/AndroidRuntime(365):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-11 00:21:38.599: E/AndroidRuntime(365):  ... 11 more

activity_main

<pre><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.src.vicnote.MainActivity"
tools:ignore="MergeRootFrame" /><code>

主碎片

Java代码

http://pastebin.com/K8eAWD2L


它在启动时就崩溃了吗? - JRowan
1
它说你的按钮为空。 - JRowan
2
дҪ иғҪеҸ‘еёғдҪ зҡ„XMLеҗ—пјҹзңӢиө·жқҘbuttonNewдёҚжҳҜactivity_main.xmlдёӯжңүж•Ҳзҡ„idгҖӮ - codeMagic
2
发布 activity_main.xml 文件。 - gunar
我正在努力修复这个丑陋的帖子,对此感到抱歉。 是的,JRowan,在启动时它会崩溃。 谢谢你们的回复 :) - user3132352
将来,您可以使用代码块而不是引用块来格式化您的Logcat。 这样会更好 :) - codeMagic
7个回答

2
从看起来的情况来看,您正在设置内容视图。
setContentView(R.layout.activity_main);

从您提供的内容来看,activity_main.xml 中没有按钮,因此会显示 nullpointerexception。

请检查您的代码并确保按钮已正确添加到布局文件中。

newButton = (Button) findViewById(R.id.buttonNew);

由于您提供的信息中实际按钮位于

fragment_main.xml

,因此该按钮为null,您可以尝试

setContentView(R.layout.fragment_main);

1
请检查您的Manifest.xml文件,确保您有某种内容。
<activity android:name=".Mainfragment" />

0
here you have to mention your button in fragment_main.xml and you have to set 

如果在setContentView()方法中使用activity_main.xml,那么如何找到你的按钮呢?只需更改xml文件名即可。

像下面这样:

setContentView(R.layout.fragment_main);


请改进你的回答。格式对内容没有任何帮助。这是非常低劣的输入... - GhostCat

0

你的xml中可能缺少一个声明

很有可能

R.id.buttonNew

为了澄清一下:你的活动正在寻找一个名为buttonNew的按钮,但没有找到它。

不,他应该在activity_main.xml中放置<Button android:id="@+id/buttonNew" ... />。 - Erik B
我认为他应该在那里寻找正确的ID。 - DigCamara
我修好了!非常感谢你。你说得对,我的按钮不在正确的XML文件中。再次感谢 :) - user3132352
很高兴能够帮助。如果您认为我回答了您的问题,请将其标记为正确答案。 - DigCamara

0
First of all , I read your all code ...Do you know, what u did big mistake..

In Activity

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            newButton = (Button) findViewById(R.id.buttonNew);

Can you check out , where your define button id in (R.layout.activity_main)

Second Mistake in Fragment

getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment())
                        .commit();
you have to call

getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();

0
package com.mvvmmodelrecyclerview;

import android.app.Activity;

import android.app.Fragment;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;



public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);




        //FragmentManager manager = getSupportFragmentManager();
        if (savedInstanceState == null) {

            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();




        }


    }




    /**
     * A placeholder fragment containing a simple view.
     */

    public static class PlaceholderFragment extends Fragment {
        Button newButton;
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            newButton = (Button) rootView.findViewById(R.id.buttonNew);
            newButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    Intent newNote = new Intent(getActivity(), NewNoteActivity.class);
                    startActivity(newNote);
                }
            });
            return rootView;
        }

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {

            super.onActivityCreated(savedInstanceState);
        }
    }


}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/MainScreen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >


    <FrameLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.src.vicnote.MainActivity"
        tools:ignore="MergeRootFrame" />
</LinearLayout>

fragment_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/MainScreen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:layout_gravity="center"
        android:id="@+id/buttonNew"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="New" />
    <TextView
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Fragmnt View" />

</LinearLayout>

0
Or if you want to add button in activity_main.xml 

just as like your code did...then try to do it proper way...like that...


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/MainScreen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <Button
        android:layout_gravity="center"
        android:id="@+id/buttonNew"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="New" />
    <FrameLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.src.vicnote.MainActivity"
        tools:ignore="MergeRootFrame" />
</LinearLayout>


fragment_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/MainScreen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:gravity="center_vertical"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Fragmnt View" />

</LinearLayout>



MainActivity.java

package com.mvvmmodelrecyclerview;

import android.app.Activity;

import android.app.Fragment;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;



public class MainActivity extends Activity {

    Button newButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        newButton = (Button) findViewById(R.id.buttonNew);
        newButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent newNote = new Intent(MainActivity.this, NewNoteActivity.class);
                startActivity(newNote);
            }
        });


        //FragmentManager manager = getSupportFragmentManager();
        if (savedInstanceState == null) {

            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();




        }


    }




    /**
     * A placeholder fragment containing a simple view.
     */

    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }
    }


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接