>source

데이터베이스에 "서비스"테이블이 있고 확인란에서 서비스 선택을 위해 어댑터 클래스를 사용하여 서비스를 가져옵니다. 체크 박스가있는 서비스를 보여줍니다. 체크 박스를 통해 고객이 선택한 주문을하고 싶습니다. 선택한 체크 박스 데이터를 Api에 전달해야합니다. 그러나 여러 개의 체크 박스 값을 서버에 전달하는 방법은 무엇입니까 ?? 도와주세요.

내 코드는 다음과 같습니다.

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
<Button
    android:id="@+id/btn_get"
    android:layout_width="91dp"
    android:layout_height="38dp"
    android:text="Place Order"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="@+id/recycler_view"
    app:layout_constraintStart_toStartOf="@+id/recycler_view"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.72"
    tools:ignore="MissingConstraints" />

Service.java

public class Service {
@SerializedName("laundry_service_id")
@Expose
String laundryServiceId;
@SerializedName("laundry_service_name")
@Expose
String laundryServiceName;
@SerializedName("laundry_service_short_form")
@Expose
String laundryServiceShortForm;
@SerializedName("laundry_order_status_id")
@Expose
String laundryOrderStatusId;
@SerializedName("laundry_service_create_by")
@Expose
String laundryServiceCreateBy;
@SerializedName("laundry_service_join_date")
@Expose
String laundryServiceJoinDate;
public Service(String laundryServiceId, String laundryServiceName,
               String laundryServiceShortForm, String laundryOrderStatusId,
               String laundryServiceCreateBy, String laundryServiceJoinDate) {
    this.laundryServiceId = laundryServiceId;
    this.laundryServiceName = laundryServiceName;
    this.laundryServiceShortForm = laundryServiceShortForm;
    this.laundryOrderStatusId = laundryOrderStatusId;
    this.laundryServiceCreateBy = laundryServiceCreateBy;
    this.laundryServiceJoinDate = laundryServiceJoinDate;
}
public String getLaundryServiceId() {
    return laundryServiceId;
}
public void setLaundryServiceId(String laundryServiceId) {
    this.laundryServiceId = laundryServiceId;
}
public String getLaundryServiceName() {
    return laundryServiceName;
}
public void setLaundryServiceName(String laundryServiceName) {
    this.laundryServiceName = laundryServiceName;
}
public String getLaundryServiceShortForm() {
    return laundryServiceShortForm;
}
public void setLaundryServiceShortForm(String laundryServiceShortForm) {
    this.laundryServiceShortForm = laundryServiceShortForm;
}
public String getLaundryOrderStatusId() {
    return laundryOrderStatusId;
}
public void setLaundryOrderStatusId(String laundryOrderStatusId) {
    this.laundryOrderStatusId = laundryOrderStatusId;
}
public String getLaundryServiceCreateBy() {
    return laundryServiceCreateBy;
}
public void setLaundryServiceCreateBy(String laundryServiceCreateBy) {
    this.laundryServiceCreateBy = laundryServiceCreateBy;
}
public String getLaundryServiceJoinDate() {
    return laundryServiceJoinDate;
}
public void setLaundryServiceJoinDate(String laundryServiceJoinDate) {
    this.laundryServiceJoinDate = laundryServiceJoinDate;
}

}

ServiceAdapter.java

public class ServiceAdapter extends RecyclerView.Adapter<ServiceAdapter.ViewHolder> {
private static List<Integer> mSelectedItemsIds;
List<Service> serviceList;
//private List<Integer> mSelectedItemsIds;
Context context;
public ServiceAdapter(List<Service> serviceList, Context context) {
    this.serviceList = serviceList;
    this.context = context;
    mSelectedItemsIds = new ArrayList<>();
}
public static List<Integer> getSelectedIds() {
    return mSelectedItemsIds;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View  view = LayoutInflater.from(context).inflate(R.layout.service_layout,parent,false);
    return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
    final Service serviceClass = serviceList.get(position);
    holder.chkbox.setText(serviceClass.getLaundryServiceName());
    holder.chkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                mSelectedItemsIds.add(position);
            }else{
                mSelectedItemsIds.remove(position);
            }
        }
    });
}
@Override
public int getItemCount() {
    return serviceList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
    CheckBox chkbox;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        chkbox=itemView.findViewById(R.id.chkbox);
    }
}

}

CheckboxActivity.java

public class CheckboxActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Service> serList;
CheckBox checkBox;
int id;
Button btn_get;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_checkbox);
    checkBox = findViewById(R.id.chkbox);
    btn_get = findViewById(R.id.btn_get);
    recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
    LinearLayoutManager LayoutManager = new LinearLayoutManager(CheckboxActivity.this, 
    LinearLayoutManager.VERTICAL,false);
    recyclerView.setLayoutManager(LayoutManager);
    btn_get.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           viewService();
        }
    });
    Call<List<Service>>call = RetrofitClient
            .getInstance()
            .getApi()
            .getServices();
    call.enqueue(new Callback<List<Service>>() {
        @Override
        public void onResponse(Call<List<Service>> call, Response<List<Service>> response) {
            serList = response.body();
            ServiceAdapter serviceAdapter = new ServiceAdapter(serList,CheckboxActivity.this);
            recyclerView.setAdapter(serviceAdapter);
            id = serList.size();
            Toast.makeText(CheckboxActivity.this,"Get the services"+id,Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onFailure(Call<List<Service>> call, Throwable t) {
            Toast.makeText(CheckboxActivity.this,"Try It" + 
    t.getMessage(),Toast.LENGTH_SHORT).show();
            System.out.println(t.getMessage());
        }
    });
}
private void viewService() {
    List<Integer> selectedid =  ServiceAdapter.getSelectedIds();
    //Log.d("List","=");
    Toast.makeText(CheckboxActivity.this,"Clicked"+selectedid,Toast.LENGTH_SHORT).show();
    for (int i = 0; i < selectedid.size(); i++) {
        int chk = selectedid.get(i);
        if (checkBox.isChecked()) {
            String ch = checkBox.getText().toString();
            Toast.makeText(CheckboxActivity.this,"Data"+ch,Toast.LENGTH_SHORT).show();
        }
    }
}
}

Api.java

@FormUrlEncoded
@POST("place_id.php")
Call<OrderResponse> place(
        @Field("list") List<Integer> selectedid);

위의 코드를 시도했습니다. Service.java 클래스 모든 서비스 응답이 체크 박스와 함께 recyclerview에 표시됩니다. 이제 선택한 확인란 값을 서버에 전달하고 싶습니다. 제발 도와주세요.


  • 답변 # 1

    당신의어댑터추가하는 클래스위치목록에mSelectedItemIds.

    mSelectedItemsIds.add(position);

    당신이해야 할 일은 객체에서 필드를 추가하는 것입니다. Service 그 목록에 클래스. 그래서 당신이 통과하고 싶다고 가정 해 봅시다. laundryServiceId 선택한 확인란 중을 서버에 추가합니다. 그런 다음이 경우 다음과 같이해야합니다.

    어댑터에서 목록 항목 유형을 문자열로 변경하십시오.

    private static List<Integer> mSelectedItemsIds;

    어댑터의 onBindViewHolder :

    if(isChecked){
    mSelectedItemsIds.add(serviceClass.getLaundryServiceId());
    }else{
    mSelectedItemsIds.remove(serviceClass.getLaundryServiceId());
    }
    
    

    그리고 통과 ServiceAdapter.getSelectedIds() 원할 때 서버에.

    이것이 문제가 해결되기를 바랍니다. 혼란이 있으면 언제든지 의견을 말하십시오.

관련 자료

  • 이전 wordpress - 사용자 정의 테이블에서 쿼리 업데이트 및 삭제가 작동하지 않는 이유는 무엇입니까?
  • 다음 prolog - 규칙이 선언 된 횟수를 세십시오SWIProlog