Как создать второй счетчик, список опций которого зависит от ввода первого счетчика?

#java #android #android-spinner

#java #Android #android-счетчик

Вопрос:

Я искал в Интернете и не смог найти решение.

То, что я пытаюсь сделать, это отобразить список массива во втором счетчике в зависимости от выбранного параметра из первого счетчика.

Логика была бы примерно такой: Если первый счетчик = CSE / IT

Тогда параметрами второго счетчика будут: 1. BCA 2. MCA

Вот мой Java-код:

 public class RegisterActivity extends AppCompatActivity implements View.OnClickListener
{
private EditText TextFname;
private EditText TextMname;
private EditText TextLname;
//private EditText TextDept;
private Spinner SpinDept;
private Spinner SpinProg;
//private EditText TextProg;
private EditText TextSemester;
private EditText TextRolln;
private EditText TextEmail;
private EditText TextPassword;
private EditText TextPasswordConfirm;

//private FirebaseFirestore db = FirebaseFirestore.getInstance();
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
private ProgressBar pBar;
private View bgBlur;

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

    TextFname = findViewById(R.id.Fname);
    TextMname = findViewById(R.id.Mname);
    TextLname = findViewById(R.id.Lname);
    //TextDept = findViewById(R.id.Dept);

    SpinDept = findViewById(R.id.Dept);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.department_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    SpinProg = findViewById(R.id.Prog);
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
            R.array.programme_array, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //TextProg = findViewById(R.id.Prog);
    TextSemester = findViewById(R.id.Semester);
    TextRolln = findViewById(R.id.Rolln);
    TextEmail = findViewById(R.id.Email);
    TextPassword = findViewById(R.id.Password);
    TextPasswordConfirm = findViewById(R.id.PasswordConfirm);

    findViewById(R.id.SubmitButton).setOnClickListener(this);
    pBar=findViewById(R.id.indeterminateBar);
    bgBlur=findViewById(R.id.bgblur);
}

//Validation method
private boolean validate()
{
    AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
    mAwesomeValidation.addValidation(TextFname, "\D ", "Invalid First Name");
    mAwesomeValidation.addValidation(TextLname, "\D ", "Invalid Last Name");
    //mAwesomeValidation.addValidation(TextDept, "\D ", "Invalid Department Name");
    //mAwesomeValidation.addValidation(TextProg, "\D ", "Invalid Programme Name");
    mAwesomeValidation.addValidation(TextSemester, "[1-9] [0-9]{0,}", "Invalid Semester (Cannot be less than 0)");
    mAwesomeValidation.addValidation(TextRolln, "[a-zA-Z-0-9\s] ", "Invalid Roll Number");
    mAwesomeValidation.addValidation(TextEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
    String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[~`!@#\$%\^amp;\*\(\)\-_\ =\{\}\[\]\|\;:"<>,./\?]).{6,}";
    mAwesomeValidation.addValidation(TextPassword, regexPassword, "Use 6 or more characters with a mix of upper amp; lower letters, numbers amp; symbols");
    mAwesomeValidation.addValidation(TextPasswordConfirm, TextPassword, "Password does not match");
    return mAwesomeValidation.validate();
}
@Override
public void onClick(View v)
{
    // Check for particular button click, because this method will be called for every
    // click on any view on which onClickListener is set as setOnClickListener(this).
    // In this case currently it doesn't matter as there is only one button, but in case
    // if you also add for example clear field button, then you need to know which
    // button was clicked.

    switch (v.getId())
    {
        case R.id.SubmitButton:
        if (validate())
        {
            String TextDept = SpinDept.getSelectedItem().toString();
            String TextProg = SpinProg.getSelectedItem().toString();


            pBar.setVisibility(View.VISIBLE);
            bgBlur.setVisibility(View.VISIBLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            //Toast.makeText(this, "Validation successful", Toast.LENGTH_SHORT).show();

            /*String Firstname = getTrimmedInput(TextFname);
            String Middlename = getTrimmedInput(TextMname);
            String Lastname = getTrimmedInput(TextLname);
            String Department = getTrimmedInput(TextDept);
            String Programme = getTrimmedInput(TextProg);
            String Semester = getTrimmedInput(TextSemester);
            String Rollnumber = getTrimmedInput(TextRolln);
            String Password = getTrimmedInput(TextPassword);*/
            String Email = getTrimmedInput(TextEmail);
            final CollectionReference dbUsers = db.collection("Students");
            final DocumentReference dbDocs = dbUsers.document(Email);
            //Student student = new Student(Firstname, Middlename, Lastname, Department, Programme, Integer.parseInt(Semester), Rollnumber, Email, Password);



            //Alternative way how to create data model. I think builder pattern is easier
            // to operate as you don't have to know in which order you should pass variables
            // (especially when you have a lot of them) to model constructor.
            // Although I don't know if my class would work as I don't know how your
            // DB backend requests data from your student class as in my model some
            // getter method name cases are different. Currently I created my Student
            // model as example and it's not used.
            final StudentImproved studentImproved =  new StudentImproved.Builder()
                .setFirstName(getTrimmedInput(TextFname))
                .setMiddleName(getTrimmedInput(TextMname))
                .setLastName(getTrimmedInput(TextLname))
                .setDepartment(TextDept)
                .setProgramme(TextProg)
                .setSemester(Integer.parseInt(getTrimmedInput(TextSemester)))
                .setRollNumber(getTrimmedInput(TextRolln))
                .setEmail(getTrimmedInput(TextEmail))
                .setPassword(getTrimmedInput(TextPassword))
                //.setPasswordConfirm(getTrimmedInput(TextPasswordConfirm))
                .build();

            dbUsers.document(Email)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
                    {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task)
                        {
                            if (task.isSuccessful())
                            {
                                if (task.getResult().exists())
                                {
                                    pBar.setVisibility(View.GONE);
                                    bgBlur.setVisibility(View.GONE);
                                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                    Toast.makeText(RegisterActivity.this, "You already have your data stored in the database", Toast.LENGTH_LONG).show();
                                }
                                else
                                    {
                                        dbDocs.set(studentImproved)

                                                .addOnSuccessListener(new OnSuccessListener<Void>()
                                                {
                                                    @Override
                                                    public void onSuccess(Void aVoid)
                                                    {
                                                        pBar.setVisibility(View.GONE);
                                                        bgBlur.setVisibility(View.GONE);
                                                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                                        Toast.makeText(RegisterActivity.this, "Successfully Registered",Toast.LENGTH_LONG).show();
                                                    }
                                                })
                                                .addOnFailureListener(new OnFailureListener()
                                                {
                                                    @Override
                                                    public void onFailure(@NonNull Exception e)
                                                    {
                                                        pBar.setVisibility(View.GONE);
                                                        bgBlur.setVisibility(View.GONE);
                                                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                                        Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                                    }
                                                });
                                    }
                            }
                        }
                    });



        }
        /*else
            {
                Toast.makeText(this, "Validation failed", Toast.LENGTH_LONG).show();
            }
            break;*/
    }
}

private String getTrimmedInput(EditText text)
{
    return text.getText().toString().trim();
}
}
  

Вот мой XML-код счетчика:

         <Spinner
            android:id="@ id/Dept"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="131dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="132dp"
            android:entries="@array/department_array"
            android:spinnerMode="dropdown"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@ id/Rolln" />

        <Spinner
            android:id="@ id/Prog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="179dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="180dp"
            android:entries="@array/programme_array"
            android:spinnerMode="dropdown"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@ id/Dept" />
  

Вот мой строковый XML-код:

     <string-array name="department_array">
    <item>Civil</item>
    <item>CSE/IT</item>
    <item>Electronics</item>
</string-array>
<string-array name="programme_array">
    <item>B.Tech Civil</item>
    <item>BCA</item>
    <item>MCA</item>
</string-array>
  

Комментарии:

1. В первом счетчике setOnItemSelectedListener Загружается второй счетчик на основе совпадения идентификатора или названия отдела

2. @AbidKhan Не могли бы вы помочь мне с кодом, пожалуйста, где я должен разместить OnItemSelectedListener? Я новичок

Ответ №1:

 spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // load spinner2 data from database method loadData
            List<String> spinner2Data= helper.loadData(spinner1.getSelectedItem().toString());

            // Create adapter for spinner
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(CurrentActivity.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,spinner2Data);

            // Drop down layout style - list view with radio button
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // attaching data adapter to spinner
            spinner2.setAdapter(dataAdapter);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });
  

Ответ №2:

В setOnItemSelectedListener первого счетчика загрузите второй счетчик на основе совпадения идентификатора или названия отдела. Поскольку вы спросили, куда поместить, setOnItemSelectedListener это должно быть внутри onCreate метода, самого первого метода вашей активности. Для этого вы можете использовать классы моделей.

 SpinProg = findViewById(R.id.Prog);

    SpinDept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
                        programmeArray.clear();
                        // Here put your logic for selecting programs against each department and initialize programmeArray then load progSpinner with that array
                         /*
               *  for(int i=0; i<totalPrograms.size; i  ){
               *
               *  
          *if(totalPrograms.get(i).getName.equals(totalDepartments.get(position).getName)){
               *  programmeArray.add(totalPrograms.get(i));
                *  }
               *  }
               * */

    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
            programmeArray, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                }

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