应用程序已停止工作 - Android

时间:2014-05-24 14:50:26

标签: java android xml

我尝试搜索类似的问题,但无法得到我想要的东西。我尝试阅读日志并搜索CAUSED BY:,这就是我得到的:

caused by : java.lang.NullPointerException

这是我的代码:

public class MainActivity extends ActionBarActivity {

    int counter;
    Button add,sub;
    TextView display;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        counter = 0;
        add = (Button)findViewById(R.id.button1);
        sub = (Button)findViewById(R.id.button2);
        display = (TextView)findViewById(R.id.text1);
        add.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                counter = counter +1;
                display.setText("your total is "+ counter);
                                        }
            });
sub.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        counter = counter -1;
        display.setText("your total is "+ counter);
                                }
        });
     }

和xml文件:

 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/ref"
    android:id="@+id/text1"
    android:layout_gravity="center"
    android:gravity="center"
    android:textSize="40sp"
/>


<Button
    android:layout_width="400dp"
    android:layout_height="wrap_content"
    android:id="@+id/button1"
    android:layout_below="@+id/text1"
    android:text="@string/refbut1"
    />
<Button
    android:layout_width="400dp"
    android:layout_height="wrap_content"
android:id="@+id/button2"
android:layout_below= "@+id/button1"
android:text="@string/refbut2"
    />

活动主xml文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/container"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.liall.tutorialfrominternet.MainActivity"
 tools:ignore="MergeRootFrame" />

1 个答案:

答案 0 :(得分:0)

下次发布问题时,请提供完整的崩溃日志,以便我们至少知道您获得异常的行。

NullPointerException是类型NullPointerException的异常,当对未初始化或使用空值初始化的对象进行引用时,jvm将通过此异常。

在这个例子中,你做了初始化的添加和子按钮,但仍然在其中一个上有NPE。 代码很好所以问题的来源可能来自环境的观点,

  1. 在运行之前,您是否清理并构建了项目?可能还没有生成xml,有时候是清理并且强制重新生成资源,更新R文件并解决资源相关的错误。

  2. 您发布的第一个xml是什么?为什么它不是FrameLayout中有根activity_main的孩子?