简体   繁体   English

注册监听器时出现NullPointerException

[英]NullPointerException when registering the Listeners

Plase have a look at the following code Plase看看下面的代码

MainActivity.java 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 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>

When I run this, I get a NullPointerException . 当我运行它时,我得到一个NullPointerException The error is happening in this place. 错误发生在这个地方。

cards.setOnClickListener(new CardsClicked());

Below is the error log 以下是错误日志

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

What is causing this error? 导致此错误的原因是什么?

UPDATE: 更新:

There are two possibilities that can happen: 有两种可能发生的可能性:

  1. You have two similar xml files with similar names. 您有两个类似名称的类似xml文件。 In one You don't have defined @id 在一个你没有定义@id
  2. You edited xml file and add an @id but somehow this xml is not rebuilded 您编辑了xml文件并添加了@id,但不知道这个xml是否已被重建

Try clean and rebuild project and check if you don't have similar files. 尝试清理并重建项目,并检查是否没有类似的文件。

I compile your code and works fine. 我编译你的代码,工作正常。 I reproduced error when I create similar file with the same @id (card_layout) add remove it from xml bonded to Activity 当我使用相同的@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

Old

You are sure its not line below ? 你确定它不在下面吗? Because I don't see any initialization of animation1 variable. 因为我没有看到animation1变量的任何初始化。

animation1.setAnimationListener(new AnimationEvent());

试试这个改变:

private class CardsClicked implements View.OnClickListener

Your Animation animation1, animation2; 你的Animation animation1, animation2; are null you have not initialized the animations for your instance. 如果为null,则表示您尚未初始化实例的动画。 That is why its giving null pointer exception. 这就是它给出空指针异常的原因。

Make sure you give the animation file before starting animation as below: 确保在开始动画之前给出动画文件,如下所示:

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

I hope you have already defined a listener new AnimationEvent() and implemented its methods to start the animation. 我希望你已经定义了一个侦听器new AnimationEvent()并实现了它的方法来启动动画。 As you have not shared any code of this listener. 因为您还没有共享此侦听器的任何代码。

I found the issue. 我发现了这个问题。 The Landscape layout is controlled by the XML file in layout-land folder. Landscape布局由layout-land文件夹中的XML文件控制。 In that folder, the ID for the LinearLayout was not provided. 在该文件夹中,未提供LinearLayout的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM