Android Fragment导致NullPointerException

时间:2014-03-10 23:48:24

标签: java android android-fragments nullpointerexception fragment

首先要说我知道这里有很多相似的帖子,我已经看过它们,但是我是Android开发的新手,我还不熟悉它修改其他答案来修复我的确切问题

我有一个默认创建的片段,其中包含一个包含按钮和文本视图的新项目,在我的MainActivity.java中,我为按钮创建了一个onClick函数。这个功能抛出了NPE。这是LogCat:

03-10 19:26:52.620: D/AndroidRuntime(878): Shutting down VM
03-10 19:26:52.620: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0xb2af2ba8)
03-10 19:26:52.630: E/AndroidRuntime(878): FATAL EXCEPTION: main
03-10 19:26:52.630: E/AndroidRuntime(878): Process: com.example.main, PID: 878 
03-10 19:26:52.630: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.main/com.example.main.MainActivity}: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.os.Handler.dispatchMessage(Handler.java:102)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.os.Looper.loop(Looper.java:136)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.ActivityThread.main(ActivityThread.java:5017)
03-10 19:26:52.630: E/AndroidRuntime(878):  at java.lang.reflect.Method.invokeNative(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878):  at java.lang.reflect.Method.invoke(Method.java:515)
03-10 19:26:52.630: E/AndroidRuntime(878):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-10 19:26:52.630: E/AndroidRuntime(878):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-10 19:26:52.630: E/AndroidRuntime(878):  at dalvik.system.NativeStart.main(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878):  at com.example.main.MainActivity.onCreate(MainActivity.java:31)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.Activity.performCreate(Activity.java:5231)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-10 19:26:52.630: E/AndroidRuntime(878):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-10 19:26:52.630: E/AndroidRuntime(878):  ... 11 more
03-10 19:31:54.292: I/Process(878): Sending signal. PID: 878 SIG: 9

MainActivity.java:

package com.example.main;

import android.support.v7.app.ActionBarActivity;
...

public class MainActivity extends ActionBarActivity {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new     PlaceholderFragment()).commit();
        }

        final TextView myText = (TextView) findViewById(R.id.text1);
        Button myButton = (Button) findViewById(R.id.button1);

        myButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                myText.setText("Yes!");
            }
        });
    }

    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

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

}  

4 个答案:

答案 0 :(得分:2)

如果TextViewButton位于布局的片段中,则需要在片段的onCreatedView方法中找到它们的ID。然后,你应该这样做:

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);
        final TextView myText = (TextView) rootView.findViewById(R.id.text1);
        Button myButton = (Button) rootView.findViewById(R.id.button1);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myText.setText("Yes!");
            }
        });
        return rootView;
    }
}

答案 1 :(得分:0)

myButton.setOnClickListener(新的View.OnClickListener()行给出了一个异常,因为它是在你启动片段之后完成的。我相信。把这些代码放在片段构造函数中,你应该很好。

答案 2 :(得分:0)

然后myButton为null。所以findViewById(R.id.button1)返回null。您应该确保这是您用于布局按钮的ID(R.layout.fragment_main)

答案 3 :(得分:0)

我在OnCreate代码中没有看到任何胎儿错误,但这里有一些解决问题的提示

1)确保activity文件中初始化了Manifest.xml

2)在评论onClickListener部分后尝试运行项目,以确保您的问题不在通货膨胀或Layout xml文件本身。

3)尝试调试OnCreate方法并通过选择变量来监控所有不同的变量值以找出问题

4)确保您的buttonTextView位于您正在膨胀的布局中

我希望我能帮忙