无法从片段将CustomDialog强制转换到适配器内部

时间:2019-06-10 17:02:26

标签: android android-fragments dialog

我有一个从片段到RecyclerView的适配器。我想从此适配器打开一个CustomDialog,并将一些信息传递给它,以使此事情我创建了一个接口,但出现此错误:

 java.lang.ClassCastException: com.ainkiwi.taskme.Fragments.UserTasksPublishedFragment cannot be cast to com.ainkiwi.taskme.FeedbackDialog$FeedbackDialogListener

Adapter类是:

public class CurrentUserTaskListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements FeedbackDialog.FeedbackDialogListener {
  private Fragment mFragment;
  public CurrentUserTaskListAdapter(Fragment mFragment, ....){
  this.mFragment = mFragment;
  }
  ...
  public void onClick(View v)
  showDialogFeedBack();
  ...
    private void showDialogFeedBack() {

    FeedbackDialog feedbackDialog = new FeedbackDialog();
    feedbackDialog.setTargetFragment(mFragment, 1);
    feedbackDialog.show(mFragment.getFragmentManager(), "FeedbackDialog");
    }

    @Override
    public void applyRatings(float skill, float timing, float chat) {
        //TODO firestore method that adds this to database
        this.skill = skill;
        this.timing = timing;
        this.chat = chat;
        Log.d("listenerCheck", "test");
    }

CustomDialog类:

public class FeedbackDialog extends AppCompatDialogFragment {
private RatingBar ratingBarSkills, ratingBarTiming, ratingBarChat;
private FeedbackDialogListener listener;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.layout_dialog_feedback, null);

    builder.setView(view)
            .setNegativeButton("Skip", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    float skill = ratingBarSkills.getRating();
                    float timing = ratingBarTiming.getRating();
                    float chat = ratingBarChat.getRating();

                    listener.applyRatings(skill, timing, chat);
                }
            });
    ratingBarSkills = view.findViewById(R.id.rbSkill);
    ratingBarTiming = view.findViewById(R.id.rbTiming);
    ratingBarChat = view.findViewById(R.id.rbChat);

    return builder.create();
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    listener = (FeedbackDialogListener) getTargetFragment();
}

public interface FeedbackDialogListener {
    void applyRatings(float skill, float timing, float chat);
    }
}

如何获得此错误?我尝试了 getTargetFragment() setTargetFragment(mFragment,1); ,就像我在许多页面上看到的那样,但到目前为止没有结果

3 个答案:

答案 0 :(得分:2)

问题在这里:

   listener = (FeedbackDialogListener) getTargetFragment();

mFragmentUserTasksPublishedFragment

并且UserTasksPublishedFragment未实现FeedbackDialogListener,这就是为什么您获得ClassCastException的原因。

添加:

您将其从适配器中删除:

@Override
    public void applyRatings(float skill, float timing, float chat) {
        //TODO firestore method that adds this to database
        this.skill = skill;
        this.timing = timing;
        this.chat = chat;
        Log.d("listenerCheck", "test");
    }

并将其添加到您的UserTasksPublishedFragment中(在实现FeedbackDialogListener之后)。

在那里,您可以将值设置为适配器(应该是一个字段)

答案 1 :(得分:0)

UserTasksPublishedFragment是(完整):

public class UserTasksPublishedFragment extends Fragment implements AvailableTaskListAdapter.OnAvailableTaskListener, CurrentUserTaskListAdapter.OnMyTaskPublishedListener, CurrentUserTaskListAdapter.OnMyTaskAssignedListener, CurrentUserTaskListAdapter.OnOtherTaskAssignedToMeListener {

    private static final String TAG = "UserTasksList";
    private FirebaseFirestore mFirestore;
    private RadioGroup radioGroup;
    private RadioButton checkedRadioButton;
    private RecyclerView rvAvailableTasks;
    private AvailableTaskListAdapter availableTaskListAdapter;
    private CurrentUserTaskListAdapter currentUserTaskListAdapter;
    private List<Task> tasksList, currentUserTasksList;
    private List<String> idTaskList, idCurrentUserTaskList;
    private int numberOfTasksAssignedToCurUser;
    private String currentLoggedUser;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_tasks_list, container, false);
        radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
        checkedRadioButton = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
        setHasOptionsMenu(true);

        mFirestore = FirebaseFirestore.getInstance();
        currentLoggedUser = SaveSharedPreference.getEmail(getActivity().getApplicationContext());

        idTaskList = new ArrayList<>();
        tasksList = new ArrayList<>();
        currentUserTasksList = new ArrayList<>();
        idCurrentUserTaskList = new ArrayList<>();
        currentUserTaskListAdapter = new CurrentUserTaskListAdapter(currentUserTasksList, idCurrentUserTaskList, getActivity(), getContext(), this, this, this, mFirestore, this);

        rvAvailableTasks = (RecyclerView) view.findViewById(R.id.rvTasks);
        rvAvailableTasks.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL));
        rvAvailableTasks.setHasFixedSize(true);
        rvAvailableTasks.setLayoutManager(new LinearLayoutManager(getActivity()));

        populateTasksAvailableList();


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // This puts the value (true/false) into the variable
                boolean isChecked = checkedRadioButton.isChecked();
                // If the radiobutton that has changed in check state is now checked...
                if (isChecked) {
                    rvAvailableTasks.setAdapter(availableTaskListAdapter);
                    availableTaskListAdapter.notifyDataSetChanged();
                } else {
                    rvAvailableTasks.setAdapter(currentUserTaskListAdapter);
                    currentUserTaskListAdapter.notifyDataSetChanged();
                }
            }
        });

        return view;
    }

    private void populateTasksAvailableList() {
        numberOfTasksAssignedToCurUser = 0;
        Log.d(TAG, "Save shared user name: " + SaveSharedPreference.getEmail(getActivity().getApplicationContext()));
        mFirestore.collection("listedTasks").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@javax.annotation.Nullable QuerySnapshot documentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.d(TAG, "Error: " + e.getMessage());
                    return;
                }
                for (DocumentSnapshot doc : documentSnapshots) {
                    Task task = doc.toObject(Task.class);

                    if (!task.getUser().equals(currentLoggedUser) && task.getAssignedTo().equals(currentLoggedUser))
                        numberOfTasksAssignedToCurUser++;

                    if (task.getUser().equals(currentLoggedUser) || task.getAssignedTo().equals(currentLoggedUser)) {
                        currentUserTasksList.add(task);
                        idCurrentUserTaskList.add(doc.getId());

                    } else {
                        if (!isTaskExpired(task) && task.getAssignedTo().isEmpty()) {
                            tasksList.add(task);
                            idTaskList.add(doc.getId());
                        }
                    }
                }
                sortTaskListChronological(currentUserTasksList);

                availableTaskListAdapter = new AvailableTaskListAdapter(tasksList, idTaskList, getActivity(), mFirestore, UserTasksPublishedFragment.this, numberOfTasksAssignedToCurUser, UserTasksPublishedFragment.this);
                availableTaskListAdapter.notifyDataSetChanged();
                currentUserTaskListAdapter = new CurrentUserTaskListAdapter(currentUserTasksList, idCurrentUserTaskList, getActivity(), getContext(), UserTasksPublishedFragment.this, UserTasksPublishedFragment.this, UserTasksPublishedFragment.this, mFirestore, UserTasksPublishedFragment.this);

                rvAvailableTasks.setAdapter(availableTaskListAdapter);
                Log.d(TAG, "numberOfTasksAssignedToCurUser " + numberOfTasksAssignedToCurUser);
            }
        });
        Log.d(TAG, "numberOfTasksAssignedToCurUser " + numberOfTasksAssignedToCurUser);
    }

    private boolean isTaskExpired(Task task) {
        Calendar curentTime = new java.util.GregorianCalendar();
        Calendar taskTime = new java.util.GregorianCalendar();
        taskTime.setTime(task.getStartDateTime());

        return curentTime.after(taskTime);
    }

    private void sortTaskListChronological(List<Task> mList) {
        if (mList.size() > 1)
            Collections.sort(mList, new Comparator<Task>() {
                @Override
                public int compare(Task o1, Task o2) {
                    return o1.getStartDateTime().compareTo(o2.getStartDateTime());
                }
            });
    }


    @Override
    public void onTaskClicked(int position) {

    }

    @Override
    public void onMyTaskAssignedClicked(int position) {

    }

    @Override
    public void onMyTaskPublishedClicked(int position) {

    }


    @Override
    public void onOtherTaskAssignedToMeClicked(int position) {

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_bar, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchView.setQueryHint("Cauta locatii");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                availableTaskListAdapter.getFilter().filter(newText);
                return false;
            }
        });

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onDestroyOptionsMenu() {
        setHasOptionsMenu(false);
    }
}

答案 2 :(得分:0)

您应该从UserTasksPublishedFragment继承您的课程FeedbackDialogListener。并覆盖所需的方法。

public class UserTasksPublishedFragment extends Fragment implements AvailableTaskListAdapter.OnAvailableTaskListener, CurrentUserTaskListAdapter.OnMyTaskPublishedListener, CurrentUserTaskListAdapter.OnMyTaskAssignedListener, CurrentUserTaskListAdapter.OnOtherTaskAssignedToMeListener,
FeedbackDialog.FeedbackDialogListener {

@Override
void applyRatings(float skill, float timing, float chat){

}
...