如何在这种情况下初始化一个变量?
问题描述:
我开始活动开始的意图取决于设备是组所有者还是仅仅是已加入的对等设备。目前,instructIntent未初始化。我是否应该按照Eclipse的建议让它变为空?或者是否有更专业的,Java代码风格的处理方式?如何在这种情况下初始化一个变量?
Intent instructIntent;
if (info.groupFormed && info.isGroupOwner) {
Log.d(WiFiDirectActivity.TAG, "DeviceDetailFragment_onCreateView: btn_ready pressed on host");
instructIntent = new Intent(getActivity(), LeaderActivity.class);
} else if (info.groupFormed) {
Log.d(WiFiDirectActivity.TAG, "DeviceDetailFragment_onCreateView: btn_ready pressed on client");
instructIntent = new Intent(getActivity(), MusicianActivity.class);
}
instructIntent.putExtra(Intent.EXTRA_TEXT, "Play");
instructIntent.putExtra(MusicService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress());
instructIntent.putExtra(MusicService.EXTRAS_GROUP_OWNER_PORT, 8080);
startActivity(instructIntent);
答
使它为空将无济于事。真正的问题是,如果info.groupFormed为false,那么instructIntent中不会有有效的值。但即使您将它初始化为null,它仍然无效。这意味着当你调用putExtra时它会抛出异常。更好的方法是要做到:
if(info.groupFormed){
if(info.isGroupOwner){
instructIntent = new Intent(getActivity(), LeaderActivity.class);
}
else{
instructIntent = new Intent(getActivity(), MusicianActivity.class);
}
//all of your putExtra and startIntent calls here
}
会注意到去认沽,并开始对意图调用所有分支机构将创建一个新的意图。这样你就不会有一个null或者单位变量试图调用成员函数。
答
任何在java中声明的变量在使用之前都应该给定值。在上面给出的代码中,如果if和else条件都不满足,我们将不会为instructIntent变量赋值。
所以你必须初始化instructIntent为null如下。
Intent instructIntent = null;
And Intent instructIntent追到第一个if? – Chucky 2013-02-13 19:11:40
是的,因为它不会在那之外使用。尽管声明它更高级不会是一个错误,只是一种风格的东西。 – 2013-02-13 19:12:30
如果没有组成组件呢? – Chucky 2013-02-13 19:14:43