Как использовать радиокнопки в ListView и обновление FireBase - PullRequest
0 голосов
/ 14 июля 2020

Я разрабатываю проект, который включает функцию фиксации посещаемости сотрудников. Я использую базу данных Fire Base в реальном времени для своего хранилища, но мне удается читать и писать в нее, кроме как с помощью радиокнопок. В одном из своих занятий (предназначенных для регистрации посещаемости) я извлекаю все данные из базы данных, объединяю их с настраиваемым представлением через настраиваемый адаптер. У меня есть два класса моделирования для пользователей и посещаемости сотрудников для моей файловой структуры JSON на Fire Base. Ниже мой java файл посещаемости сотрудников.

Итак, мне нужно знать, как использовать параметры переключателя в моем адаптере, чтобы я мог коллективно использовать эту информацию для записи в узел посещаемости моей базы данных.

Надеюсь, что у меня все ясно.

//Define all view objects    
define a list to store all the users firebase database
List<Users> mUserList;
//Create my reference database objects
DatabaseReference mDataBaseRef;
DatabaseReference mAttendanceDataBaseRef;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_employee_attendance_registry);
    //Assign all views
    
    //Assign our list to be an ArrayList to be able to store users
    mUserList = new ArrayList<>();

    //Instantiate database reference object to point at Employee node on the database
    mDataBaseRef = FirebaseDatabase.getInstance().getReference("Employee");
    //Get today's date and send it to the activity
    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
    String strDate = formatter.format(date);
    currentAttedanceDate.setText(strDate);
    saveRegistryBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
            String strDate = formatter.format(date);
            SaveAttendanceReg(strDate);
        }
    });
}

Затем я вызываю свою функцию сохранения, чтобы создать узел посещаемости сотрудников в моей базе данных, чтобы написать о посещаемости всех моих сотрудников, как это

    private void SaveAttendanceReg(String mCurretAttedanceDate) {
    mAttendanceDataBaseRef = FirebaseDatabase.getInstance().getReference("EmployeeAttendance");
    for(int i=0;i<Attendance_Custom_Adapter.mUserList.size();i++){
        Users theUser = Attendance_Custom_Adapter.mUserList.get(i);
        Attendance mAttendancies = new Attendance(theUser.getDatabaseEmployeeID(),
        theUser.getName(),theUser.getSurname(),mCurretAttedanceDate,theUser.isPresent);
      }
   }

Мой пользователь java файл модели базы данных выглядит следующим образом:

public class Users {
public String email, name, surname, location, userID, mDatabaseEmployeeID;
public boolean isPresent;

public Users() {
}

public Users(String email, String name, String surname, String location, 
String userID, String mDatabaseEmployeeID) {
    this.email = email;
    this.name = name;
    this.surname = surname;
    this.location = location;
    this.userID= userID;
    this.mDatabaseEmployeeID = mDatabaseEmployeeID;
}

// with all my getters and setters
}

Моя посещаемость java файл модели базы данных выглядит следующим образом:

public class Attendance {
String mUserDatabaseID, userName,
        surname, attendanceDate;
boolean attendanceStatus;
public Attendance(){

}
public Attendance(String userDatabaseID, String userName, String surname, 
    String attendanceDate, boolean attendanceStatus) {
    mUserDatabaseID = userDatabaseID;
    this.userName = userName;
    this.surname = surname;
    this.attendanceDate = attendanceDate;
    this.attendanceStatus = attendanceStatus;
}

//With all my getters and setters
}

Мой пользовательский адаптер как показано ниже:

public class Attendance_Custom_Adapter extends BaseAdapter {
private Activity context;
public static List<Users> mUserList;
private int positions;
public boolean attendaStatus;
LayoutInflater inflter;

public Attendance_Custom_Adapter(Activity context, List<Users> mUserList) {
    //super(context, R.layout.attendance_custom_list_layout,mUserList);
    this.context = context;
    this.mUserList = mUserList;
}


@Override
public int getCount() {
    return mUserList.size(); //.length;
}


@Override
public long getItemId(int position) {
    return 0;
}

@Override
public Users getItem(int position) {
    return mUserList.get(position);
}


@NonNull
@Override
public View getView(final int position, /*@Nullable*/ View convertView, /*@NonNull*/ ViewGroup
parent) {
    LayoutInflater mInflater = context.getLayoutInflater();
    View mListViewItem = mInflater.inflate(R.layout.attendance_custom_list_layout,parent,false);

    TextView textViewEmployName = mListViewItem.findViewById(R.id.employeeName_layout_ID);
    TextView textViewSurname = mListViewItem.findViewById(R.id.employeeSurmane_layout_ID);
    RadioButton absentRadioBtn = mListViewItem.findViewById(R.id.absentRadioBtnId);
    RadioButton presentRadioBtn = mListViewItem.findViewById(R.id.presentRaioBtnId);

    //Users user = mUserList.get(position);
    Users user = this.getItem(position);
    this.positions = position;

    textViewEmployName.setText(user.getName());
    textViewSurname.setText(user.getSurname());


    absentRadioBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                
               //My issue is here. How do I handle these Radio Buttons.                    

            }
        }
    });
    presentRadioBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                
                 //My issue is here. How do I handle these Radio Buttons.
                
            }
        }
    });
    return mListViewItem;
     }
  }

Вот мой собственный макет;

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

<TextView
    android:id="@+id/nameLabelId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Name :"
    android:textSize="15dp"
    android:textStyle="bold"
    android:layout_marginRight="3dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"/>

<TextView
    android:id="@+id/employeeName_layout_ID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:text="TextView"
    android:textSize="15dp"
    android:textStyle="normal"
    app:layout_constraintStart_toEndOf="@+id/nameLabelId"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/employeeSurnameId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/nameLabelId"
    app:layout_constraintStart_toStartOf="@+id/nameLabelId"
    android:text="Surname :"
    android:textSize="15dp"
    android:textStyle="bold"
    />
<TextView
    android:id="@+id/employeeSurmane_layout_ID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toEndOf="@+id/employeeSurnameId"
    app:layout_constraintTop_toTopOf="@+id/employeeSurnameId"
    android:layout_weight="2.6"
    android:text="TextView"
    android:textSize="15dp"
    android:textStyle="normal"/>

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:orientation="horizontal"
    tools:layout_editor_absoluteX="160dp"
    tools:layout_editor_absoluteY="10dp">

    <RadioButton
        android:id="@+id/absentRadioBtnId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:buttonTint="@android:color/holo_blue_dark"
        android:text="@string/absent" />

    <RadioButton
        android:id="@+id/presentRaioBtnId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:buttonTint="@android:color/holo_blue_dark"
        android:text="@string/present" />
</RadioGroup>

<TextView
    android:id="@+id/EmployeeDatabaseID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/employeeName_layout_ID"
    app:layout_constraintEnd_toEndOf="parent"
    android:visibility="invisible"/>

</androidx.constraintlayout.widget.ConstraintLayout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...