Search code examples
androidlistviewandroid-arrayadapter

Change text of listview in onItemClick (listview is filled by a string-array/arrayAdapter)


I want to change the text in my listview. In my onCreate I fill my listview and setting an OnItemClicklistener:

onCreate:

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, trainingstage);

setListAdapter(adapter);

ListView listView = getListView();

listView.setOnItemClickListener(this);

onItemClick:

public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {

TextView tv = (TextView)view.findViewById(android.R.id.text1);

    switch (position) {

    case 0:

        tv.setText("Hello");

        IF I CLICK TEXT SHOULD CHANGE!
        break;

That works fine, but if I restart the activity the old text is back. I want to change the text forever, if I click on the listitem!


Solution

  • You can achieve this by two options:

    Easier way
    Change text in trainingstage and set string array to STATIC!

    Better way
    If you want to save the text after click, you need some kind of database to store the change. Either use sqlite if you want to save different text. If number of text is fixed, better to use SharedPreferences. You would also need to restore the text from here to set the TextView on Activity start.