从硬编码字符串数组切换到getStringArray()时崩溃

时间:2015-04-30 09:05:24

标签: java android arrays string android-arrayadapter

我有一个简单的ArrayAdapter,里面填充了一个字符串数组。

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            inflater.getContext(), android.R.layout.simple_list_item_1,
            numbers_text);

当我传入这样的字符串时,一切正常。

String[] numbers_text = new String[] { "one", "two", "three", "four" };

但是当我以这种方式声明字符串时,它会崩溃。

Resources res = getResources();
String[] numbers_text = res.getStringArray(R.array.Planets);

我在这里缺少任何逻辑错误吗?

xml string array:

<string-array name="Planets">
    <item>Sun</item>
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
</string-array>

编辑:发布已更新的代码,其中字符串声明已移至函数

public class SimpleListFragment extends ListFragment
{
Resources res = getActivity().getResources();

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    String[] numbers_digits = res.getStringArray(R.array.Planets);
    new CustomToast(getActivity(), numbers_digits[(int) id]);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    String[] numbers_text = res.getStringArray(R.array.Planets);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            inflater.getContext(), android.R.layout.simple_list_item_1,
            numbers_text);
    setListAdapter(adapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}
}

2 个答案:

答案 0 :(得分:3)

要访问您需要有效using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hotel_Check_In { class Program { static void Main(string[] args) { string lead = "JohnSmith"; Room room = Room.rooms.AsEnumerable() .Where(x => x.LeadName.LeadName == lead).FirstOrDefault(); } } public class Room { public static List<Room> rooms = null; public int RoomNumber; public string RoomType; public string SmokingAllowed; public Boolean booked; public Guest LeadName; public Room(int numberOfRooms) { for (int i = 1; i <= numberOfRooms; i++) { Room newRoom = new Room(); rooms.Add(newRoom); newRoom.RoomNumber = i; } } } public class Guest { public string LeadName; public int roomNumber; public Guest(string name, int roomN) { LeadName = name; roomNumber = roomN; } } }的资源。移动Context的初始化,例如,在回调中 numbers_text

onCreateView

答案 1 :(得分:0)

您可以使用变量res,但可以在onCreate(...)中启动它,例如:

public class SimpleListFragment extends ListFragment
{
    Resources res;

    @Override
    onCreate(...)
    {
        res = getActivity().getResources();

    } 

}

然后你在课堂范围内使用res