注册监听器时出现NullPointerException

时间:2013-12-09 06:15:47

标签: java android eclipse user-interface onclicklistener

Plase看看下面的代码

MainActivity.java

public class MainActivity extends Activity {

    private TextView words;
    private Map<String, String> wordsMap;
    private List wordList;
    private Animation animation1, animation2;
    private LinearLayout cards;

    private int displayIndex = 0;
    private static final int ENGLISH = 1;
    private static final int BRAZIL = 2;
    private int languageDisplaying;

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

        words = (TextView)findViewById(R.id.word);
        cards = (LinearLayout)findViewById(R.id.cards_layout);

        languageDisplaying = ENGLISH;

        animation1 = AnimationUtils.loadAnimation(this, R.anim.to_middle);
        animation2 = AnimationUtils.loadAnimation(this, R.anim.from_middle);

        wordsMap = new HashMap<String, String>();
        wordsMap.put("Dog", "Perro");
        wordsMap.put("Cat", "Gato");
        wordsMap.put("Universe", "Universo");
        wordsMap.put("Telephone", "Teléfono");
        wordsMap.put("KeyBoard", "TecladoDel");
        wordsMap.put("Country", "País");

        wordList = new ArrayList<String>();
        wordList.add("Dogsssssssssss");
        wordList.add("Cat");
        wordList.add("Universe");
        wordList.add("Telephone");
        wordList.add("KeyBoard");
        wordList.add("Country");

        words.setText(wordList.get(0).toString());

        //Registering Listeners
        words.setOnClickListener(new TextClicked());
        cards.setOnClickListener(new CardsClicked());
        animation1.setAnimationListener(new AnimationEvent());
    }

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

    //Animation Listener
    private class AnimationEvent implements AnimationListener
    {
        String str = "";

        @Override
        public void onAnimationEnd(Animation arg0) {
            // TODO Auto-generated method stub
            if(languageDisplaying==ENGLISH)
            {
                str = wordList.get(displayIndex).toString();


                words.setText(wordsMap.get(str));
                words.setTextColor(Color.BLUE);

                languageDisplaying = BRAZIL;

            }
            else
            {
                str = wordList.get(displayIndex).toString();

                words.setText(str);
                words.setTextColor(Color.BLACK);

                languageDisplaying = ENGLISH;
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationStart(Animation animation) {
            // TODO Auto-generated method stub

        }

    }

    private OnTouchListener textViewSwiped = new OnSwipeTouchListener()
    {
        public boolean onSwipeLeft() 
         {
            return true;
         }
    };

    private class TextClicked implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            words.startAnimation(animation1);



        }

    }

    private class CardsClicked implements View.OnClickListener
    {

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

        }

    }

    private void showMenu()
    {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.glass_menu);
        dialog.show();
    }

}

activity_main.xml中

<LinearLayout 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:orientation="vertical"
    android:gravity="center"
    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=".MainActivity" >

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="202dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="100 de 554" />

    <LinearLayout 
        android:id="@+id/cards_layout"
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:background="@drawable/round_corners"
        android:clickable="true"
        android:gravity="center">

        <TextView
        android:id="@+id/word"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Text"
        android:textSize="50sp" />

    </LinearLayout>

</LinearLayout>

当我运行时,我得到一个NullPointerException。错误发生在这个地方。

cards.setOnClickListener(new CardsClicked());

以下是错误日志

12-09 06:05:24.040: E/AndroidRuntime(2424): FATAL EXCEPTION: main
12-09 06:05:24.040: E/AndroidRuntime(2424): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.googleglass_demo/com.example.googleglass_demo.MainActivity}: java.lang.NullPointerException
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.os.Looper.loop(Looper.java:137)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.ActivityThread.main(ActivityThread.java:5041)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at java.lang.reflect.Method.invokeNative(Native Method)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at java.lang.reflect.Method.invoke(Method.java:511)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at dalvik.system.NativeStart.main(Native Method)
12-09 06:05:24.040: E/AndroidRuntime(2424): Caused by: java.lang.NullPointerException
12-09 06:05:24.040: E/AndroidRuntime(2424):     at com.example.googleglass_demo.MainActivity.onCreate(MainActivity.java:71)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.Activity.performCreate(Activity.java:5104)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-09 06:05:24.040: E/AndroidRuntime(2424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-09 06:05:24.040: E/AndroidRuntime(2424):     ... 11 more

导致此错误的原因是什么?

4 个答案:

答案 0 :(得分:1)

<强>更新

有两种可能发生的可能性:

  1. 您有两个类似名称的类似xml文件。在一个你没有定义@id
  2. 您编辑了xml文件并添加了@id,但不知道这个xml是否已重建
  3. 尝试清理并重建项目并检查您是否没有类似的文件。

    我编译你的代码并且工作正常。当我使用相同的@id(card_layout)添加从xml绑定到Activity

    的删除它时,我再现了错误
    05-02 09:06:19.514: ERROR/AndroidRuntime(519): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stacktest/com.example.stacktest.MyActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
        at android.app.ActivityThread.access$2300(ActivityThread.java:125)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:4627)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:521)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
        at com.example.stacktest.MyActivity.onCreate(MyActivity.java:38)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
        ... 11 more
    

    <强>旧

    你确定它不在下面吗?因为我没有看到animation1变量的任何初始化。

    animation1.setAnimationListener(new AnimationEvent());
    

答案 1 :(得分:1)

尝试此更改:

private class CardsClicked implements View.OnClickListener

答案 2 :(得分:0)

您的Animation animation1, animation2;为空,但您尚未初始化实例的动画。这就是它给出空指针异常的原因。

确保在开始动画之前给出动画文件,如下所示:

  // load the animation
    animation1= AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.<yourfileName>);  
  animation1.setAnimationListener(new AnimationEvent());

我希望你已经定义了一个监听器new AnimationEvent()并实现了它的方法来启动动画。因为您还没有共享此侦听器的任何代码。

答案 3 :(得分:0)

我发现了这个问题。 Landscape布局由layout-land文件夹中的XML文件控制。在该文件夹中,未提供LinearLayout的ID。