添加监听器后,我的活动崩溃了

时间:2014-04-26 18:14:14

标签: java android android-activity fragment

我在MainActivity课程中有这段代码:

public class MainActivity extends ActionBarActivity {
    Button   mButton;
    EditText mEdit;

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

        mButton = (Button)findViewById(R.id.btnAsk);
        mEdit   = (EditText)findViewById(R.id.txtQuestion);

        mButton.setOnClickListener(
                new View.OnClickListener()
                {
                    public void onClick(View view)
                    {
                        Toast.makeText(getApplicationContext(),
                        mEdit.getText().toString(), Toast.LENGTH_SHORT).show();
                    }
                });

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

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

}

一切都很好,但在setOnClickListener()添加mButton之后,它就开始崩溃了。

以下是错误日志:

04-26 14:12:26.255: E/AndroidRuntime(1447): FATAL EXCEPTION: main
04-26 14:12:26.255: E/AndroidRuntime(1447): Process: com.gelasoft.answeringball, PID: 1447
04-26 14:12:26.255: E/AndroidRuntime(1447): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gelasoft.answeringball/com.gelasoft.answeringball.MainActivity}: java.lang.NullPointerException
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.os.Looper.loop(Looper.java:136)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at java.lang.reflect.Method.invokeNative(Native Method)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at java.lang.reflect.Method.invoke(Method.java:515)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at dalvik.system.NativeStart.main(Native Method)
04-26 14:12:26.255: E/AndroidRuntime(1447): Caused by: java.lang.NullPointerException
04-26 14:12:26.255: E/AndroidRuntime(1447):     at com.gelasoft.answeringball.MainActivity.onCreate(MainActivity.java:30)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.Activity.performCreate(Activity.java:5231)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 14:12:26.255: E/AndroidRuntime(1447):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 14:12:26.255: E/AndroidRuntime(1447):     ... 11 more

我在这里缺少什么?我知道它确实很小,但我现在无法发现它。

P.S这是我的片段xml:

<RelativeLayout 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"
    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="com.xx.ss.MainActivity$PlaceholderFragment" >

    <ImageView
        android:id="@+id/sphereIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/magicBallDescr"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:id="@+id/table"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/sphereIcon"
        android:orientation="vertical" >

        <TextView 
            android:id="@+id/txtAnswer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />

        <EditText
            android:id="@+id/txtQuestion"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/textHint"
            android:inputType="textMultiLine" 
            android:lines="8"
            />

        <Button 
            android:id="@+id/btnAsk"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:text="@string/btnAskQ"     
            android:paddingEnd="@dimen/activity_vertical_margin"      
         />
    </LinearLayout>

</RelativeLayout>

2 个答案:

答案 0 :(得分:2)

替换

mButton = (Button)findViewById(R.id.btnAsk);

mButton = (Button)rootView.findViewById(R.id.btnAsk);  // this will go in Fragment onCreateView

将setOnClicklistener代码也移动到onCreateView。

希望它有所帮助。

答案 1 :(得分:1)

移动此代码:

mButton.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    Toast.makeText(getApplicationContext(),
                    mEdit.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

进入片段的onCreateView()方法。它应该工作。