java - Android 中按钮设置为 Null 并生成 NullPointerException

标签 java android xml android-intent

我正在尝试制作一个具有不同 Intent 的应用程序。我已经准备好两个了我希望第一个 Intent 中的按钮使第二个 Intent 出现。 问题是该按钮始终设置为 null,并在应用程序运行时抛出 NullPointerException

我的 .java 类是:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(vocabulario);

   //....

    Button buttonVocabulary = (Button) findViewById(R.id.buttonVocabulary);
    Button holaPlayerBtn = (Button) findViewById(R.id.holaPlayerBtn);
//...
    buttonVocabulary.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view)
        {
//Se abre un nuevo Intent con el primer botón
            try
            {
                {
                    Intent myIntent = new Intent(view.getContext(), Vocabulario.class);
                    startActivityForResult(myIntent, 0);}
            } catch (Exception e) {
                e.printStackTrace();
            }
        }});

我的 main.xml 文件是:

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:id="@+id/adViewContainer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            />

        <Button
            android:id="@+id/buttonVocabulary"
            android:text="@string/vocabulario"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:nestedScrollingEnabled="true" />
    </LinearLayout>
</LinearLayout>

在我的 AndroidManifest.xml 中有一个元素表示:

<activity android:name=".Vocabulario"
        android:label="@string/vocabulario"/>

我做错了什么。你能帮我解决这个问题吗? 提前致谢。

最佳答案

改变

setContentView(vocabulario);

setContentView(R.layout.main);

关于java - Android 中按钮设置为 Null 并生成 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37542621/

相关文章:

Java XPath 查询没有在节点中获取文本?

java - 为什么当我更改最大堆大小时 Eclipse 打不开?

java - 如何更改 AsyncTask 中的 ListView?

java - 我的牛顿 Gradle 代码不起作用。我该如何解决?

java - 如何计算最常用的应用程序?

android - 电源按钮在 AndEngine 游戏中创建问题

jquery - ajax xml 出现空数据错误

java - Android - 如何使用 Android 4.0 下载 XML 文件?

java - Android 页面在图片下载过程中崩溃

java - 使用 Robolectrics 和 Mockito 来模拟/ stub 函数调用发出 http 请求,但它不起作用