javaandroidxmlandroid-layoutandroid-spinner

How do I get Android Spinner Text to Update?


I have a spinner inside my activity.

spinner

The top spinner bar is to act as a title, I then have a navigation bar below that and in the bottom half I have a fragment container.

The spinner contains a list of all of the exercises which it is passed.

enter image description here

After clicking one of the items inside the spinner drop down, I would like the spinner text to be updated, however no change occurs...

I get the following messages:

W/e.exerciseappv: Accessing hidden field Landroid/widget/AbsListView;->mIsChildViewEnabled:Z (greylist, reflection, allowed)

D/OpenGLRenderer: endAllActiveAnimators on 0xc6707410 (DropDownListView) with handle 0xc6e4a5f0

How can I get my basic spinner working (alternatively does anyone have a work-around) ?

Activity



import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import com.example.exerciseappv5.Fragments.ExerciseGraphFragment;
import com.example.exerciseappv5.Fragments.RecordExerciseFragment;
import com.example.exerciseappv5.Fragments.RecordExerciseHistoryFragment;
import com.example.exerciseappv5.ViewModels.ChildExerciseViewModel;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;

public class RecordExerciseActivity2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    List<String> allChildExerciseNames = new ArrayList<>();
    public static final String PARENT_EXERCISE_ID = "-999";
    public static final String EXTRA_DATE = "com.example.exerciseappv4.EXTRA_DATE";
    public static final String EXTRA_WEEK_DATES = "1";
    public static String EXTRA_JUNCTIONID = "EXERCISE_JUNCTION_ID";
    int parentExerciseID;
    private ChildExerciseViewModel childExerciseViewModel;
    String firstExerciseName;
    String selectedExercise;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_exercise);

        getSupportActionBar().hide();

        Intent intent = getIntent();
        if (intent.hasExtra(PARENT_EXERCISE_ID)) {
            parentExerciseID = Integer.parseInt(intent.getStringExtra(PARENT_EXERCISE_ID));
        }

        BottomNavigationView bottomNav = findViewById(R.id.top_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, new RecordExerciseFragment()).commit();

        //getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
        childExerciseViewModel = ViewModelProviders.of(this).get(ChildExerciseViewModel.class);
        childExerciseViewModel.getChildExerciseNameFromParentID(parentExerciseID).observe(this, this::setChildExerciseName);
        childExerciseViewModel.getAllchildExercisesFromParentID(parentExerciseID).observe(this, this::getAllChildExercisesFromParentID);


        Spinner spinner =  findViewById(R.id.spinner1);
        ArrayList<String> spinnerStringArray = new ArrayList<>();
        //Add your data to your array
        spinnerStringArray.addAll(allChildExerciseNames);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
               android.R.layout.simple_spinner_dropdown_item, allChildExerciseNames);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        selectedExercise = parent.getItemAtPosition(position).toString();
        Toast.makeText(parent.getContext(), selectedExercise, Toast.LENGTH_SHORT).show();
        Log.i("spinner item clicked ", selectedExercise);
    }

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

    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.nav_track:
                            selectedFragment = new RecordExerciseFragment();
                            break;
                        case R.id.nav_history:
                            selectedFragment = new RecordExerciseHistoryFragment();
                            break;
                        case R.id.nav_exercise_list:
                            selectedFragment = new ExerciseGraphFragment();
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, selectedFragment).commit();
                    return true;
                }
            };

    private void setChildExerciseName(String childExerciseName) {
        firstExerciseName = childExerciseName;
    }

    public String getSelectedExercise() {
        return selectedExercise;
    }

    private void getAllChildExercisesFromParentID(List<String> allChildExercisesReceived) {
        allChildExerciseNames.addAll(allChildExercisesReceived);
    }
}


Activity Layout XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <View style="@style/Full_Divider"
        android:id="@+id/divider9"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:layout_below="@+id/spinner1"/>

    <View style="@style/Full_Divider"
        android:id="@+id/divider10"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:layout_below="@+id/top_navigation" />


    <FrameLayout
        android:id="@+id/fragment_container2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/divider10" />

    <androidx.appcompat.widget.AppCompatSpinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"

        android:layout_marginEnd="1dp"
        android:layout_marginRight="1dp"
        android:gravity="right"
        android:padding="8dp" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/top_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner1"
        app:itemTextColor="#ffffff"
        app:itemIconTint="#ffffff"
        app:menu="@menu/top_navigation"
        android:background="#292929" />

</RelativeLayout>

build.Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.exerciseappv5"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8

        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

    def lifecycle_version = "1.1.1"
    def room_version = "1.1.1"

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0-rc01'
    implementation 'androidx.cardview:cardview:1.0.0'




    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'android.arch.lifecycle:extensions:1.0.0-alpha1'
    annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'

    implementation 'android.arch.persistence.room:runtime:1.0.0-alpha1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha1'
}

Solution

  • Currently you are doing the whole setup for the Spinner in onCreate(): you instantiate the adapter with a (possibly empty) data list and call spinner.setAdapter(spinnerAdapter);

    After that you only change the data list: each time that getAllChildExercisesFromParentID(List<String>) is called, you add a couple of Strings to the data list which you passed into the adapter. But you never call notifyDatasetChanged() on the adapter, and I think this is where things start going wrong.

    The runtime does not throw an Exception (as would have been the case with ListView instead of Spinner if I remember correctly) - you just see an empty(!) Spinner with a non-empty dropdown list, and selecting an item does not have any effect.

    So to fix your issue, you can either recreate a new adapter for the Spinner when getAllChildExercisesFromParentID(List<String>) is called. In this case you need to make the Spinner a field of your Activity, so that it can be accessed from this method:

    private Spinner spinner;
    

    Initialize it in onCreate() but don't set the adapter yet:

    spinner =  findViewById(R.id.spinner1);
    spinner.setOnItemSelectedListener(this);
    

    Create a new instance of the adapter for the Spinner when you receive the data:

    private void getAllChildExercisesFromParentID(List<String> allChildExercisesReceived){
        // maybe removing old data is a good idea?
        allChildExerciseNames.clear();
    
        allChildExerciseNames.addAll(allChildExercisesReceived);
     
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, allChildExerciseNames);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
    
    }
    

    Or you let your Activity have a field private ArrayAdapter<String> spinnerAdapter;

    Initialize the Spinner completely in onCreate():

    Spinner spinner =  findViewById(R.id.spinner1);
    spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, allChildExerciseNames);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerAdapter);
    
    spinner.setOnItemSelectedListener(this);
    

    ... and update the data list (and consequently the adapter) when you receive the data:

    private void getAllChildExercisesFromParentID(List<String> allChildExercisesReceived){
        // remove old data 
        allChildExerciseNames.clear();
    
        allChildExerciseNames.addAll(allChildExercisesReceived);
        spinnerAdapter.notifyDataSetChanged();
    }
    

    I like the second version better because it does not need to create a new object each time the data is refreshed - it can help to improve performance (but in this case the effect on modern devices will hardly be noticeable, so it's more a matter of code style)

    BTW of course you can and should keep the Spinner in your layout - the AppCompatSpinner was just my attempt at getting rid of the weird "Landroid/widget/AbsListView..." message which just happened to pop up at the same time as the Spinner problem.