java - 无法找出空指针异常

标签 java android

好吧,我几个小时以来一直在努力寻找解决方案,但我找不到。 这是我的代码,日志猫说空指针期望是:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class splash extends Activity{
Button begin;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    begin=(Button) findViewById(R.id.button);
    begin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent startmenu=new Intent("com.life.project.menu");
            startActivity(startmenu);
        }
    });
}

}

这是 xml 文件:

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

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="You have 20 minutes to increase your status as much as possible." />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Begin!"
    android:layout_gravity="center"
    android:typeface="monospace" />

 </LinearLayout>

所以当我尝试运行它时,它得到一个空指针异常,我不知道它出了什么问题,有什么想法吗?

最佳答案

您需要在findViewById之前调用setContentView:

setContentView(R.layout.the_layout_xml_name);
begin=(Button) findViewById(R.id.button);
// ...

关于java - 无法找出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644688/

相关文章:

java - 连接超时时从 Netty 发送未经请求的 408 响应

java - liblpsolve55.so : cannot open shared object file: No such file or directory

java - 如何通过javafx(tabpane,menebutton)将一些具有不同默认布局的UI集成在一起?

Android ListView 滚动到顶部时自动加载更多数据

eclipse : Unable to resolve target 'android-xx' 中的 Android 错误

javascript - 如何从第二个 Web View 访问我的应用程序的 ionic 存储 (localForage)?

java - 将数组转换为列表时出现编译器错误?

java - 使用 openSession() 而不是 getCurrentSession() - 何时以及为什么?

android - Syncano 类和 SyncanoDashboard 之间有什么区别?

android - 给Android中Viewpager的PagerTabStrip添加样式