您的位置:首页 > 其它

布局文件的NullPointerException

2016-12-21 11:12 281 查看
今天早上写了一个小程序,简单到不行的,就是一个ListView现实数据,代码如下

public class MainActivity extends AppCompatActivity {

private ListView mListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listview1);

ArrayList<String> strings = new ArrayList<>();
for (int i = 0; i < 0; i++) {
String str = "this is item" + i;
strings.add(str);
}

mListView.setAdapter(new MyAdapter(strings));

}


还有一个MyAdapter类就不贴了。

第一次运行没有问题,后来想在这个界面中再添加一个ListView,就修改了下布局

<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"
>

<ListView
android:id="@+id/listview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

<view
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>

<ListView
android:id="@+id/listview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>


中间添加了一个view横线区分,可是添加以后,程序就一直抛出异常

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean java.lang.String.equals(java.lang.Object)’ on a null object reference

空指针异常,毫不相关嘛,我的程序又没有使用equals比较,怎么会有空指针呢?后来思考,既然是添加可布局之后报错了,肯定是布局文件的问题(当然这是在查找了一番代码之后才这么想的,以后要吸取教训)经过一番查找终于找到了原因,注意看布局文件中的view横线

<view
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>


view的标签是小写,正确的写法是将View的首字母大写。太隐蔽了,Studio也不提示。希望大家注意
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐