空指针异常的原因是什么?

时间:2014-07-09 07:06:49

标签: android android-activity onclicklistener

我是Android编程的初学者。我正在编写一个简单的代码,在主要活动中单击按钮后,它会打开第二个活动。但是应用程序不能在模拟器中打开,在logcat中我不断获得空指针异常。请帮我纠正这个。

MainActivity.java

      package com.example.whyprocastinate;

      import android.support.v7.app.ActionBarActivity;
      import android.support.v4.app.Fragment;
      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.View.OnClickListener;
      import android.view.ViewGroup;
      import android.widget.Button;

      public class MainActivity extends ActionBarActivity {

        Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1 = (Button) findViewById(R.id.button1);
    this.setClickListener();

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

  private void setClickListener(){
    b1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            startSecondActivity();  
        }
    }); 
  }

    private void startSecondActivity(){
    Intent intent = new Intent(this, EnterTask.class);
    this.startActivity(intent);
 }

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

  }`

这是logcat显示的内容


07-09 02:18:27.673: W/dalvikvm(1082): threadid=1: thread exiting with uncaught exception   (group=0xb2b02ba8)

07-09 02:18:27.693: E/AndroidRuntime(1082): FATAL EXCEPTION: main
07-09 02:18:27.693: E/AndroidRuntime(1082): Process: com.example.whyprocastinate, PID: 1082
07-09 02:18:27.693: E/AndroidRuntime(1082): java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.example.whyprocastinate/com.example.whyprocastinate.MainActivity}: java.lang.NullPointerException

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.ActivityThread.access$800(ActivityThread.java:135)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.os.Handler.dispatchMessage(Handler.java:102)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.os.Looper.loop(Looper.java:136)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.ActivityThread.main(ActivityThread.java:5017)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at java.lang.reflect.Method.invokeNative(Native Method)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at java.lang.reflect.Method.invoke(Method.java:515)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at dalvik.system.NativeStart.main(Native Method)

07-09 02:18:27.693: E/AndroidRuntime(1082): Caused by: java.lang.NullPointerException

07-09 02:18:27.693: E/AndroidRuntime(1082):     at com.example.whyprocastinate.MainActivity.setClickListener(MainActivity.java:33)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at com.example.whyprocastinate.MainActivity.onCreate(MainActivity.java:24)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.Activity.performCreate(Activity.java:5231)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

07-09 02:18:27.693: E/AndroidRuntime(1082):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

07-09 02:18:27.693: E/AndroidRuntime(1082):     ... 11 more

07-09 02:18:31.023: I/Process(1082): Sending signal. PID: 1082 SIG: 9`

MainActivity.java中的第33行是

b1.setOnClickListener(new View.OnClickListener(){

Fragement_main.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"
tools:context="com.example.whyprocastinate.MainActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/heading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerInParent="true"
    android:layout_marginTop="10dp"
    android:textSize="23sp"
    android:text="@string/heading" />

<Button 
    android:id="@+id/button1"
    android:text="+"        
    android:layout_width="40dp"
    android:layout_height="55dp"
    android:layout_marginTop="0dp"
    android:layout_alignParentRight="true"
    android:layout_alignBottom="@+id/heading"
    android:background="@drawable/button1"               
    />

</RelativeLayout>

&#39; EnterTask&#39;是第二个活动。这是一项空白活动,我还没有在其中添加任何代码。

1 个答案:

答案 0 :(得分:0)

Try This Code:-

package com.example.whyprocastinate;

      import android.support.v7.app.ActionBarActivity;
      import android.support.v4.app.Fragment;
      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.View.OnClickListener;
      import android.view.ViewGroup;
      import android.widget.Button;

      public class MainActivity extends ActionBarActivity {

        Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1 = (Button) findViewById(R.id.button1);
    this.setClickListener();

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

  private void setClickListener(){
    b1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            startSecondActivity();  
        }
    }); 
  }

    private void startSecondActivity(){
    Intent intent = new Intent(this, EnterTask.class);
    this.startActivity(intent);
 }

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

Button button = (Button) rootView.findViewById(R.id.button1);
            button.setOnClickListener(new OnClickListener() {

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

                Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();  

                }
            });
        return rootView;
      }
   }

  }