繁体   English   中英

空指针异常Android

[英]Null Pointer Exception Android

我正在尝试制作一个按钮,计算点击次数并将其显示在文本视图中。 尝试了我所知道的一切。 XML:

       <LinearLayout
        android:id="@+id/gpulay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="20dp" >
        <TextView
            android:id="@+id/master_control_text_gpulay"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Master Control :"
            android:textAppearance="?android:attr/textAppearanceMedium" />
        <Button
            android:id="@+id/plus_gpulay"
            android:layout_width="35dp"
            android:layout_height="35dip"/>
    </LinearLayout>

这是我的代码:

public class Main extends Fragment { 

    int c=0;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }

        ListView GPU_LAYOUT = (ListView)inflater.inflate(R.layout.gpu, container, false);

        TextView text = (TextView) GPU_LAYOUT.findViewById(R.id.text1);
        Button plus = (Button) GPU_LAYOUT.findViewById(R.id.butt1);

        plus.setOnClickListener(new OnClickListener() {     //null pointer this line, but it's from .srtText i think
            public void onClick(View v) {
                c++;
                text.setText(c);
            }
        });

    }

    return GPU_LAYOUT;
}

当我打开App Force时,它会关闭,所以我什至看不到主要布局。

NPE从这里来

text.setText(c);

您使用了错误的setText()方法。 当您在其中放置一个int时,它将查找具有该idresource 您需要给它一个String 您可以通过几种方法执行此操作。 一种方法是将其更改为

text.setText("" + c);

你也可以

text.setText(String.valueOf(c));

TextView文档注意到不同的方法。

在Activity中工作时在onCreateView中创建您的应用程序是完全错误的。

您仍然可以在onCreate方法中完成所有这些操作。

我的猜测是GPU_Layout为null或不包含您的按钮。 这就是为什么按钮(加号)为Null并在其上调用setOnClickListener会引发NullPointerException的原因。

如果您可以解释错误发生的时间,膨胀/构建活动期间或实际按下按钮的过程,这也将有所帮助

1)您需要从Fragment而不是Activity扩展您的类。 然后,您的onCreateView方法将起作用。 然后将此片段设置为Activity的contentView。

2)您不能将int设置为textView或任何其他小部件的文本。 您需要先使用String.valueOf(count);将其转换为String String.valueOf(count);

暂无
暂无

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

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