Java ANDROID:If...Else 作为 Switch on String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3820256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ANDROID: If...Else as Switch on String
提问by neildeadman
I'm writing an Android app for work that shows the status of our phone lines, but thats neither here nor there.
我正在编写一个用于工作的 Android 应用程序,它显示我们电话线的状态,但这既不存在也不存在。
I make a call to one of our servers and get returned JSON text of the status. I then parse this putting each line into a SortedMap (TreeMap) with the Key being the name of the line and my own class as the value (which holds status and other details).
我调用我们的其中一台服务器并获得返回的状态的 JSON 文本。然后,我将每一行解析为一个 SortedMap (TreeMap),其中 Key 是行的名称,我自己的类作为值(保存状态和其他详细信息)。
This all works fine.
这一切正常。
When the app runs it should then show each line and the info I have retrieved, but nothing gets updated.
当应用程序运行时,它应该显示每一行和我检索到的信息,但没有任何更新。
The JSON is returned and added to the Map correctly.
返回 JSON 并正确添加到 Map 中。
This is a snapshot of the code that isn't working. I simply iterate through the map and depending on the value of key update the relevant TextView. The problem I am having is that when it gets to the IF statement that matches it never runs that code. It skips it as if values don't match.
这是不起作用的代码的快照。我只是遍历地图并根据键的值更新相关的 TextView。我遇到的问题是,当它到达匹配的 IF 语句时,它永远不会运行该代码。它跳过它,好像值不匹配一样。
I can't see any errors. Is this the only way to do this as I know you can't use Switch..Case etc?
我看不到任何错误。这是我知道您不能使用 Switch..Case 等的唯一方法吗?
Can anyone see my error? I've been coding on Android for 1 week now so its probably a newbie error!!
谁能看到我的错误?我已经在 Android 上编码了 1 周,所以它可能是新手错误!!
Thanks Neil
谢谢尼尔
Iterator iterator = mapLines.entrySet().iterator();
while(iterator.hasNext())
{
// key=value separator this by Map.Entry to get key and value
Map.Entry<String, Status> mapEntry = (Map.Entry<String, Status>)iterator.next();
// getKey is used to get key of Map
String key = (String)mapEntry.getKey();
// getValue is used to get value of key in Map
Status value = (Status)mapEntry.getValue();
if(key == "Ski")
{
TextView tvStatus = (TextView)findViewById(R.id.SkiStatus);
tvStatus.setText(value.Status);
}
else if(key == "Cruise")
{
TextView tvStatus = (TextView)findViewById(R.id.CruiseStatus);
tvStatus.setText(value.Status);
}
else if(key == "Villas")
{
TextView tvStatus = (TextView)findViewById(R.id.VillasStatus);
tvStatus.setText(value.Status);
}
}
采纳答案by Joachim Sauer
You must use equals()
to compare String
objects in Java. Otherwise you just compare if the two objects are the same instance of the String
classand don't compare their actual content:
您必须使用equals()
来比较String
Java 中的对象。否则,你只是比较,如果两个对象是相同的实例String
类,不比较它们的实际内容:
if (key.equals("Ski")) {
...
}
Or, to avoid a NullPointerException
if key
might be null
:
或者,为了避免NullPointerException
ifkey
可能是null
:
if ("Ski".equals(key)) {
...
}
回答by Dead Programmer
checking key with the string literal "Ski", you can use like below . This will prevent nullpointer exception.
使用字符串文字“Ski”检查键,您可以像下面这样使用。这将防止空指针异常。
if ("Ski".equals(key))
{
...
}
回答by Janusz
I prefer to use maps in this case because they eliminate the need for duplicated code and long if else constructs. I don't know where in your code this snippet occurs so this may not apply in your case but just to mention it.
在这种情况下,我更喜欢使用映射,因为它们消除了对重复代码和长 if else 构造的需要。我不知道此代码段出现在您的代码中的哪个位置,因此这可能不适用于您的情况,只是提一下。
Use a Map to get the correct resource for your String and set the status.
使用 Map 为您的 String 获取正确的资源并设置状态。
The code would look something like this:
代码看起来像这样:
First initialize the map:
首先初始化地图:
Map<String, Integer> textViews = new HashMap<String, Integer>();
textViews.put("Ski", R.id.Ski);
textViews.put("Cruise", R.id.Cruise);
textViews.put("Villas", R.id.Villas);
Then retrieve the correct id and set the text:
然后检索正确的 id 并设置文本:
((TextView) findViewById(textViews.get(key))).setText(status);
This will reduce the big if else construct a lot and adding a textview will be as easy as changing the map.
这将减少大量的 if else 构造,并且添加 textview 将像更改地图一样容易。