Search code examples
javaandroidandroid-layoutandroid-listviewandroid-listfragment

Strings not being assigned to list view items


I am trying to use some strings from the strings.xml file for names of items for my list view but during deployment, my app won't run. I've looked in many areas of the Internet for relevant tutorials but all of them just show strings that have been hard-coded. Does anyone know what is wrong with my code and how to fix it using strings and not hard coding?

    public class FragmentLineChooserList extends android.support.v4.app.Fragment {

        ListView list_linechooser;

        String[] listContent = {
                getResources().getString(R.string.item_0),
                getResources().getString(R.string.item_1),
                getResources().getString(R.string.item_2)
        };

        private boolean mTwoPane;

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
            View v = inflater.inflate(R.layout.fragment_line_chooser_list, container, false);

            list_linechooser = (ListView)v.findViewById(R.id.list_linechooser);
        MyColoringAdapter adapter = new MyColoringAdapter(getActivity(),listContent);
        list_linechooser.setAdapter(adapter);
       );

        return v;
    }

    private class MyColoringAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;

        public MyColoringAdapter(Context context, String[] values) {
            super(context, R.layout.list_item, values);
            this.context = context;
            this.values = values;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.list_item, parent, false);
            TextView textView = (TextView) rowView.findViewById(R.id.list_item);
            textView.setText(values[position]);
            int textColorId = R.color.white; // Default color
            switch (position) {
                case 0:
                    textColorId = R.color.red; break;
                case 1:
                    textColorId = R.color.yellow; break;
                case 2:
                    textColorId = R.color.green; break;
            }
            textView.setTextColor(getResources().getColor(textColorId));
            return rowView;
        }
    }
}

Solution

  • Do like

      String[] listContent = {
                getActivity().getResources().getString(R.string.item_0),
                getActivity().getResources().getString(R.string.item_1),
                getActivity().getResources().getString(R.string.item_2)
        };
    

    under onCreateView(...)