首页 > 解决方案 > 由 1st Spinner 创建的 2nd Spinner 应该更新 textview

问题描述

第一个微调器根据所选项目添加第二个微调器的数组列表。无论选择第一个 Spinner,文本视图始终更新到第二个 Spinner 的第一项,但是当从第二个 Spinner 中选择另一个项目(例如第二个项目)时它不会更新,变量“emailname”和“emailto”也是如此" 即使“emailto”变量在其余活动中具有相同的值。“emailname”证明它不是另一个“emailto”,因为它不会根据来自 2nd Spinner 的其余项目更改值。

活动有效,但价值没有改变。

我尝试在 if 语句的外部/内部添加 runOnUiThread,使 t1.setValue 在外部单独使用 runOnUiThread。没用。

我添加了一个 s2.setOnItemSelectedListener(this); 它使第二个微调器的选定项目始终粘在第一个项目上。

StudentAppointmentActivity.java

package com.example.collegeinfobotjava;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

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

public class StudentAppointmentActivity extends AppCompatActivity implements OnItemSelectedListener {

    Spinner s1,s2;
    TextView t1;
    Button b1;
    EditText e1;
    ImageButton bck;
    FirebaseAuth firebaseauth;
    DatabaseReference databaseReference;
    String uid,emailfrom,emailto,dep,emailnameto;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studentappointment);


        t1 = findViewById(R.id.textviewwhomname);
        e1 = findViewById(R.id.editTextTextMultiLine);
        s1 = findViewById(R.id.spinnerdepartment);
        s2 = findViewById(R.id.spinnertowhom);
        b1 = findViewById(R.id.buttonstdappemailsend);
        bck = findViewById(R.id.imageButtonbck);


        firebaseauth = FirebaseAuth.getInstance();
        emailfrom = FirebaseAuth.getInstance().getCurrentUser().getEmail();
        uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

        s1.setOnItemSelectedListener(this);

       

        b1.setOnClickListener(view -> {
            if (s1.getSelectedItem().toString().equals("-")) {
                Toast.makeText(StudentAppointmentActivity.this, "Please choose which department", Toast.LENGTH_SHORT).show();

            }
            else {
               sendEmail();
            }
        });

        bck.setOnClickListener(view -> goBack());

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        String sp1 = String.valueOf(s1.getSelectedItem());


        if (sp1.contentEquals("Applied Sciences")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            list.add("HoS-Applied Biology");
            list.add("HoS-Applied Chemistry");
            list.add("HoS-Environmental Sciences");
            list.add("HoS-Physics Unit");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter.notifyDataSetChanged();
            s2.setAdapter(dataAdapter);
            dep="Applied Sciences";

            if(s2.getSelectedItem().toString().equals("HoD")){
                emailnameto="DR. AFRAA AL ADAWI";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-Applied Biology")){
                emailnameto="Dr. Umaima Hamad Al Hoqaniya";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-Applied Chemistry")){
                emailnameto="Dr. Wafa Mustafa Al-Lawati";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-Environmental Sciences")){
                emailnameto="Dr. Suad Said Al-Kindi";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-Physics Unit")){
                emailnameto="Mr. Shabbir Ahmed Nadeem";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }

        if (sp1.contentEquals("Business Studies")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            list.add("HoS-HRM");
            list.add("HoS-Marketing");
            list.add("HoS-Accounting");
            ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter2.notifyDataSetChanged();
            s2.setAdapter(dataAdapter2);
            dep="Business Studies";
            if(s2.getSelectedItem().toString().equals("HoD")){
                emailnameto="DR. BASSAM KHALIL HAMDAN TABASH";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-HRM")){
                emailnameto="Dr. Fayza Salim Awlad Thani";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-Marketing")){
                emailnameto="Ms. M. Seema";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("HoS-Accounting")){
                emailnameto="Dr. Yousif Mohammed Al Balushi";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }

        if (sp1.contentEquals("Engineering")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            ArrayAdapter<String> dataAdapter3 = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter3.notifyDataSetChanged();
            s2.setAdapter(dataAdapter3);
            dep="Engineering";

            if(s2.getSelectedItem().toString().equals("HoD")){
                emailnameto="Dr. Yahya Obaid Bakheet Al Shamsi";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }

        if (sp1.contentEquals("Fashion Design")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            ArrayAdapter<String> dataAdapter4 = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter4.notifyDataSetChanged();
            s2.setAdapter(dataAdapter4);
            dep="Fashion Design";
            if(s2.getSelectedItem().toString().equals("HoD")){
                emailnameto="MS. SALWA SULTAN MOHAMMED AL-HABSI";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }

        if (sp1.contentEquals("Information Technology")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            list.add("PC-Database");
            list.add("PC-Networking");
            list.add("PC-Software Engineering");
            list.add("PC-Internet and E-Security");
            list.add("PC-Information Systems");
            ArrayAdapter<String> dataAdapter5 = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter5.notifyDataSetChanged();
            s2.setAdapter(dataAdapter5);
            dep="Information Technology";
            if(s2.getSelectedItem().toString().equals("HoD")){
                emailnameto="DR. HUDA AL SHUAILY";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("PC-Database")){
                emailnameto="Mr. Gregorio A. Dela Cruz Jr.";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("PC-Networking")){
                emailnameto="Mr. Russell Diona";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("PC-Software Engineering")){
                emailnameto="Imad Al Barwani";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("PC-Internet and E-Security")){
                emailnameto="Mr. Muhammed Raheez";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
            if(s2.getSelectedItem().toString().equals("PC-Information Systems")){
                emailnameto="Dr. Muna Saif Humaid Al Rahbi";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }

        if (sp1.contentEquals("Pharmacy")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            ArrayAdapter<String> dataAdapter6 = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter6.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter6.notifyDataSetChanged();
            s2.setAdapter(dataAdapter6);
            dep="Pharmacy";
            if(s2.getSelectedItem().toString().equals("HoD")){
                emailnameto="DR. MUNA ARIF MANSOOR AL JUMA";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }

        if (sp1.contentEquals("Photography")) {
            List<String> list = new ArrayList<>();
            list.add("HoD");
            ArrayAdapter<String> dataAdapter7 = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter7.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter7.notifyDataSetChanged();
            s2.setAdapter(dataAdapter7);
            dep="Photography";
            if (s2.getSelectedItem().toString().equals("HoD")) {
                emailnameto="MR. BEN DEGEDEH";
                t1.setText(emailnameto);
                emailto="16j15144@stu.hct.edu.om";
            }
        }



    }

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

    }


    public void goBack(){
        startActivity(new Intent(getApplicationContext(),StudentHomeActivity.class));
        finish();
    }

    protected void sendEmail() {

        DatabaseReference databaseforeignReference = FirebaseDatabase.getInstance().getReference().child("student");

        databaseforeignReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String stdid=dataSnapshot.child(uid).child("sid").getValue().toString();


         databaseReference = FirebaseDatabase.getInstance().getReference().child("appointment").child(uid).push();
        HashMap<String, String> userMap = new HashMap<>();
        userMap.put("department", dep);
        userMap.put("discussed", e1.getText().toString());
        userMap.put("to_whom", emailnameto);
        userMap.put("studentid", stdid);
        databaseReference.setValue(userMap);

                String mEmail = emailto;
                String mSubject = "Appointment with "+stdid+" Student";
                String mMessage = e1.getText().toString();


                JavaMailAPI javaMailAPI = new JavaMailAPI(StudentAppointmentActivity.this, mEmail, mSubject, mMessage);

                javaMailAPI.execute();
                Toast.makeText(StudentAppointmentActivity.this, "Submitted", Toast.LENGTH_SHORT).show();

          }


            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }

        });

    }
}

学生约会.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <Button
        android:id="@+id/buttonstdappemailsend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:text="Setup"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/editTextTextMultiLine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="9dp"
        android:ems="10"
        android:gravity="start|top"
        android:inputType="textMultiLine"
        android:maxLines="6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewdiscussed" />


    <Spinner
        android:id="@+id/spinnerdepartment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="162dp"
        android:entries="@array/department"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Spinner
        android:id="@+id/spinnertowhom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="42dp"
        android:layout_marginBottom="67dp"
        app:layout_constraintBottom_toTopOf="@+id/textviewwhomname"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textviewtowhom" />

    <TextView
        android:id="@+id/textviewstdappdep"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginBottom="25dp"
        android:text="Department"
        app:layout_constraintBottom_toTopOf="@+id/spinnerdepartment"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textviewtowhom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="185dp"
        android:layout_marginEnd="379dp"
        android:text="To"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewdiscussed" />

    <TextView
        android:id="@+id/textviewwhomname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/buttonstdappemailsend"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="Timing : Thursday, 10am -12 noon \nNote: Each student will take only 10 minutes.\nPlease make your appointment two (2) days before setting it up."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textViewdiscussed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="Items to be Discussed:"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinnerdepartment" />

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageButton
            android:id="@+id/imageButtonbck"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="#00FFFFFF"
            android:scaleType="fitCenter"
            app:layout_constraintEnd_toStartOf="@+id/toolbar"
            app:layout_constraintHorizontal_bias="0.207"
            app:srcCompat="@drawable/abc_vector_test" />

    </androidx.appcompat.widget.Toolbar>
</androidx.constraintlayout.widget.ConstraintLayout><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <Button
        android:id="@+id/buttonstdappemailsend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:text="Setup"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/editTextTextMultiLine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="9dp"
        android:ems="10"
        android:gravity="start|top"
        android:inputType="textMultiLine"
        android:maxLines="6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewdiscussed" />


    <Spinner
        android:id="@+id/spinnerdepartment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="162dp"
        android:entries="@array/department"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Spinner
        android:id="@+id/spinnertowhom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="42dp"
        android:layout_marginBottom="67dp"
        app:layout_constraintBottom_toTopOf="@+id/textviewwhomname"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textviewtowhom" />

    <TextView
        android:id="@+id/textviewstdappdep"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginBottom="25dp"
        android:text="Department"
        app:layout_constraintBottom_toTopOf="@+id/spinnerdepartment"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textviewtowhom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="185dp"
        android:layout_marginEnd="379dp"
        android:text="To"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewdiscussed" />

    <TextView
        android:id="@+id/textviewwhomname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/buttonstdappemailsend"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="Timing : Thursday, 10am -12 noon \nNote: Each student will take only 10 minutes.\nPlease make your appointment two (2) days before setting it up."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textViewdiscussed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="Items to be Discussed:"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinnerdepartment" />

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageButton
            android:id="@+id/imageButtonbck"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="#00FFFFFF"
            android:scaleType="fitCenter"
            app:layout_constraintEnd_toStartOf="@+id/toolbar"
            app:layout_constraintHorizontal_bias="0.207"
            app:srcCompat="@drawable/abc_vector_test" />

    </androidx.appcompat.widget.Toolbar>
</androidx.constraintlayout.widget.ConstraintLayout>

示例 1: A1 A2

示例 2: B1 B2

标签: javaandroidfirebase-realtime-database

解决方案


看起来您只为第一个微调器设置了 OnItemSelectedListener。您还必须为第二个微调器设置 OnItemSelectedListener。

s1.setOnItemSelectedListener(this);
s2.setOnItemSelectedListener(this);

之后,您必须使用微调器 ID 处理 OnItemSelectedListener。

  @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.spinnerdepartment) {
            //Do whatever you want when item selected from the first spinner
        } else {
            //Do whatever you want when item selected from the second spinner
        }
    }

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

    }

除了实现 OnItemSelectedListener 之外,您还可以像下面这样设置 OnItemSelectedListener,而无需为您的类实现 OnItemSelectedListener:

s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            }

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

s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            }

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

您还可以对情况使用相同的代码(例如设置适配器等)。我建议对相同代码使用方法并在方法中处理变体。您的代码看起来会更干净,并且易于阅读和处理。

public class StudentAppointmentActivity  extends AppCompatActivity{

    Spinner s1,s2;
    TextView t1;
    Button b1;
    EditText e1;
    ImageButton bck;
    FirebaseAuth firebaseauth;
    DatabaseReference databaseReference;
    String uid,emailfrom,emailto,dep,emailnameto;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studentappointment);


        t1 = findViewById(R.id.textviewwhomname);
        e1 = findViewById(R.id.editTextTextMultiLine);
        s1 = findViewById(R.id.spinnerdepartment);
        s2 = findViewById(R.id.spinnertowhom);
        b1 = findViewById(R.id.buttonstdappemailsend);
        bck = findViewById(R.id.imageButtonbck);

        firebaseauth = FirebaseAuth.getInstance();
        emailfrom = FirebaseAuth.getInstance().getCurrentUser().getEmail();
        uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

        b1.setOnClickListener(view -> {
            if (s1.getSelectedItem().toString().equals("-")) {
                Toast.makeText(StudentAppointmentActivity.this, "Please choose which department", Toast.LENGTH_SHORT).show();

            }
            else {
                sendEmail();
            }
        });

        bck.setOnClickListener(view -> goBack());

        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setAdapter(listForS2(position));
                dep = deps(position);
            }

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

            }
        });

        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                emailnameto = emailNameTo(s1.getSelectedItemPosition()).get(position);
                t1.setText(emailnameto);
                emailto = emailTo(s1.getSelectedItemPosition()).get(position);
            }

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

            }
        });

    }

    private void setAdapter(List<String> list) {
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s2.setAdapter(dataAdapter);
    }

    private String deps(int position) {
        return position == 0 ? "Applied Sciences" : position == 1 ? "Business Studies" : position == 2 ? "Engineering" : position == 3
                ? "Fashion Design" : position == 4 ? "Information Technology" : position == 5 ? "Pharmacy" : "Photography";
    }

    private List<String> emailNameTo(int position) {
        List<String> list = new ArrayList<>();
        if (position == 0) {
            list.add("DR. AFRAA AL ADAWI");
            list.add("Dr. Umaima Hamad Al Hoqaniya");
            list.add("Dr. Wafa Mustafa Al-Lawati");
            list.add("Dr. Suad Said Al-Kindi");
            list.add("Mr. Shabbir Ahmed Nadeem");
        } else if (position == 1) {
            list.add("DR. BASSAM KHALIL HAMDAN TABASH");
            list.add("Dr. Fayza Salim Awlad Thani");
            list.add("Ms. M. Seema");
            list.add("Dr. Yousif Mohammed Al Balushi");
        } else if (position == 2) {
            list.add("Dr. Yahya Obaid Bakheet Al Shamsi");
        } else if (position == 3) {
            list.add("MS.SALWA SULTAN MOHAMMED AL -HABSI");
        }else if(position == 4){
            list.add("DR. HUDA AL SHUAILY");
            list.add("Mr. Gregorio A. Dela Cruz Jr.");
            list.add("Mr. Russell Diona");
            list.add("Imad Al Barwani");
            list.add("Mr. Muhammed Raheez");
            list.add("Dr. Muna Saif Humaid Al Rahbi");
        }else if(position == 5){
            list.add("DR. MUNA ARIF MANSOOR AL JUMA");
        }else{
            list.add("MR. BEN DEGEDEH");
        }
        return list;
    }

    private List<String> emailTo(int position) {
        List<String> list = new ArrayList<>();
        if (position == 0) {
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
        } else if (position == 1) {
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
        } else if (position == 2) {
            list.add("16j15144@stu.hct.edu.om");
        } else if (position == 3) {
            list.add("16j15144@stu.hct.edu.om");
        }else if(position == 4){
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
            list.add("16j15144@stu.hct.edu.om");
        }else if(position == 5){
            list.add("16j15144@stu.hct.edu.om");
        }else{
            list.add("16j15144@stu.hct.edu.om");
        }
        return list;
    }

    private List<String> listForS2(int position) {
        List<String> list = new ArrayList<>();
        if (position == 0) {
            list.add("HoD");
            list.add("HoS-Applied Biology");
            list.add("HoS-Applied Chemistry");
            list.add("HoS-Environmental Sciences");
            list.add("HoS-Physics Unit");
        } else if (position == 1) {
            list.add("HoD");
            list.add("HoS-HRM");
            list.add("HoS-Marketing");
            list.add("HoS-Accounting");
        } else if (position == 4) {
            list.add("HoD");
            list.add("PC-Database");
            list.add("PC-Networking");
            list.add("PC-Software Engineering");
            list.add("PC-Internet and E-Security");
            list.add("PC-Information Systems");
        } else {
            list.add("HoD");
        }
        return list;
    }

    public void goBack(){
        startActivity(new Intent(getApplicationContext(),StudentHomeActivity.class));
        finish();
    }

    protected void sendEmail() {
        DatabaseReference databaseforeignReference = FirebaseDatabase.getInstance().getReference().child("student");

        databaseforeignReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String stdid=dataSnapshot.child(uid).child("sid").getValue().toString();

                databaseReference = FirebaseDatabase.getInstance().getReference().child("appointment").child(uid).push();
                HashMap<String, String> userMap = new HashMap<>();
                userMap.put("department", dep);
                userMap.put("discussed", e1.getText().toString());
                userMap.put("to_whom", emailnameto);
                userMap.put("studentid", stdid);
                databaseReference.setValue(userMap);

                String mEmail = emailto;
                String mSubject = "Appointment with "+stdid+" Student";
                String mMessage = e1.getText().toString();

                JavaMailAPI javaMailAPI = new JavaMailAPI(StudentAppointmentActivity.this, mEmail, mSubject, mMessage);

                javaMailAPI.execute();
                Toast.makeText(StudentAppointmentActivity.this, "Submitted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }

        });

    }
}

推荐阅读