试图找到解决方案,当我尝试这样做时,程序会以某种方式崩溃。
我的代码出了什么问题,找不到它为什么会这样做的原因?
无论如何,在程序的其他部分非常接近的类似工作正常吗?
解释我的问题的一点代码..
my.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switch();
}
public void switch() {
RelativeLayout chatsLayout = (RelativeLayout)findViewById(R.id.chatsLayout);
RelativeLayout chats = (RelativeLayout) chatsLayout.findViewById(R.id.chats);
chats.setVisibility(View.GONE);
RelativeLayout noChats = (RelativeLayout) chatsLayout.findViewById(R.id.noChats);
noChats.setVisibility(View.GONE);
}
my.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/chatsLayout"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<RelativeLayout
android:id="@+id/chats"
android:visibility="gone"
android:padding="8dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
<RelativeLayout
android:id="@+id/noChats"
android:padding="8dp"
android:visibility="visible"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
</RelativeLayout>
以下是来自logcat的错误代码:
08-10 08:06:00.922 2736-2736/fi.hgs.apps E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: fi.hgs.apps, PID: 2736
java.lang.RuntimeException: Unable to start activity ComponentInfo{fi.hgs.apps/fi.hgs.apps.ChatsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.RelativeLayout.findViewById(int)' on a null object reference
这个
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.RelativeLayout.findViewById(int)' on a null object reference
答案 0 :(得分:2)
你的onCreate应该是这样的:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
switch();
}
您的切换方法应如下所示:
public void switch() {
RelativeLayout chatsLayout = (RelativeLayout)findViewById(R.id.chatsLayout);
RelativeLayout chats = (RelativeLayout)findViewById(R.id.chats);
chats.setVisibility(View.GONE);
RelativeLayout noChats = (RelativeLayout)findViewById(R.id.noChats);
noChats.setVisibility(View.GONE);
}
既然你的所有观点; chatsLayout,chats和noChats在你的活动中膨胀的同一个xml中定义,你可以直接在它们上调用findViewById。
答案 1 :(得分:1)
在setContentView()
中致电onCreate()
,然后使用findViewById()
找到它。否则,您将获得NullPointerException
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
switch();
}