user3087000 user3087000 - 4 months ago 11
Android Question

Android - Why the string returned by getResources().getStringArray cannot be used in if clause?

My arrays.xml:

<string-array name="chart_names">
<item>abc</item>
</string-array>


My testing code:

String[] chartNames = getActivity().getResources().getStringArray(R.array.chart_names);

if ("abc" == chartNames[0]) {
Log.v("msg", "yes");
}else{
Log.v("msg", "no");
}


I always get false, so the console always prints "no".

Why does this happened ? It's really strange.....

Please help me....... Thanks.

Answer

The best practice is use equals() to compare strings or any objects

Try this code:

String[] chartNames = getActivity().getResources().getStringArray(R.array.chart_names);

if (chartNames[0].equals("abc")) {
  Log.v("msg", "yes");
}else{
  Log.v("msg", "no");
}
Comments