Я пытался вызвать метод действия из моего адаптера представления переработчика.То, что я сделал,
Я создал интерфейс, реализовал для требуемой операции переопределение его метода и пытался вызвать из адаптера
Я получаю java.lang.ClassCastException: android.app.Applicationневозможно привести к my.package.Interface.InterfaceName
Ниже приведен код
MethodCaller.java
public interface MethodCaller {
void deleteAddress(String did);
}
AddressAdapter.java
public class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.ViewHolder> {
private Context context;
private List<Address> list;
public AddressAdapter(Context context, List<Address> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public AddressAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.address_single, parent, false);
return new AddressAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull AddressAdapter.ViewHolder holder, final int position) {
Address address = list.get(position);
holder.btn_deleteAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Address address = list.get(position);
final String id = address.getId();
//if(context instanceof MethodCaller){
((MethodCaller)context).deleteAddress(id); //ClassCastException - Error
//}
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public Button btn_deleteAddress;
public ViewHolder(View itemView) {
super(itemView);
btn_deleteAddress = itemView.findViewById(R.id.btn_deleteAddress);
}
}
}
AddressActivity.java
public class AddressActivity extends AppCompatActivity implements MethodCaller {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address);
//CODE
}
}
@Override
public void deleteAddress(String did) {
Toast.makeText(this, did, Toast.LENGTH_SHORT).show();
/*DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
deleteAddressRequest(id);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to delete this item?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();*/
}
}