javaandroidarraylistonitemselectedlistener

Best way to implement ArrayList in Android Studio


i have 30 items in ArrayList and its implement in Spinner, i placed it in java file like this

ArrayList<String> listProblemSolving = new ArrayList<>();
    listProblemSolving.add("List1");
    listProblemSolving.add("List2");
    listProblemSolving.add("List3");
    listProblemSolving.add("List4");
    listProblemSolving.add("List5");
    listProblemSolving.add("List6");
    listProblemSolving.add("List7");
    ...
    ArrayAdapter<String> adapterProblemSolving = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, listProblemSolving);

and i implement in spinner like this

sp.setAdapter(adapterProblemSolving);

The question is, can i store the list item in strings file? And is there any simply way if i want to give different action to item list, for example i try this one

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             if (position == 1)
                // do something

             if (position == 2)
                // do something

             ...
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Thank you and sorry i you found this as dupplicate question.


Solution

  • Well, if your entries are simple strings then you can try this

    In your strings.xml

    <string-array name="data_array">
       <item>value 1</item>
       <item>value 2</item> 
       <item>value 3</item>
     </string-array>
    

    In your xml layout for spinner

    <Spinner  
     ... 
     ...
    android:entries="@array/data_array" />