简体   繁体   中英

How to access variable from spinner listener?

I have the following code, in which I want to access 'selectedTeam' at the button listener.

        //Adding setOnItemSelectedListener method on spinner.
        sTeams.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                selectedTeam = parent.getItemAtPosition(position).toString();
                editText.setText(selectedTeam, TextView.BufferType.EDITABLE);
            }

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

        buttonApply.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                String editedName = editText.getText().toString();
                // Here I want to access selectedTeam
            }
        });

I tried to declare the variable outside the method but that gives the error 'Variable 'selectedTeam'is accessed from within inner class, needs to be declared final'. I tried that, but that doesn't work since final Strings cannot be changed.

Use class member instead.

In JLS 8.1.3. Inner Classes and Enclosing Instances :

When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used.

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

It means you can only use an outside final variable or an enclosing class member in an anonymous inner class.

[...]
private String selectedTeam;
[...]

//Adding setOnItemSelectedListener method on spinner.
    sTeams.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            selectedTeam = parent.getItemAtPosition(position).toString();
            editText.setText(selectedTeam, TextView.BufferType.EDITABLE);
        }

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

    buttonApply.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            String editedName = editText.getText().toString();
            if (selectedTeam != null && !"".equals(selectedTeam)) {
                // Do something
            }
        }
    });

You need to declare your variable global.

public class MainActivity extends AppCompatActivity {

String selectedteam;
...
buttonApply.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            String editedName = editText.getText().toString();
            selectedteam = editedName; // or whatever you want
        }
    });

In my case I use shared preference to store the value and get that value where i want to use.

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "selectedTeam");
editor.apply();

How to get value:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("name", null);

Hope it helps

you need to do it in a different way. This work for me, i've implemented the activity with AdapterView.OnItemSelectedListener and View.OnClickListener and override the methods.

You can now access to selectedTeam from the OnClick method.

(if you use the xml file, think to change the package of your app)

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,View.OnClickListener{

    Spinner sTeam;
    EditText editText;
    Button button;
    String selectedTeam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sTeam = (Spinner) findViewById(R.id.spinner_team);
        button = (Button) findViewById(R.id.confirmation_button);
        editText = (EditText) findViewById(R.id.edittext_team);


        List<String> spinnerArray =  new ArrayList<String>();
        spinnerArray.add("team1");
        spinnerArray.add("team2");
        spinnerArray.add("team3");

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

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sTeam.setAdapter(adapter);

        button.setOnClickListener(this);
        sTeam.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        selectedTeam = parent.getItemAtPosition(position).toString();
        editText.setText(selectedTeam, TextView.BufferType.EDITABLE);
    }

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

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case (R.id.confirmation_button) :{
                //You can access to selected team here
            }break;
        }
    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yourpackage.test">

    <Spinner
        android:id="@+id/spinner_team"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/confirmation_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/edittext_team"
        app:layout_constraintLeft_toRightOf="@+id/edittext_team"
        android:layout_marginLeft="8dp" />

    <EditText
        android:id="@+id/edittext_team"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinner_team" />

</android.support.constraint.ConstraintLayout>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM