使用片段将数据从一个片段传输到另一个片段时获取错误

时间:2016-10-27 06:24:29

标签: android interface fragment communication

public class MistakeGridFragment extends Fragment {

private Set<String> mistakeSelected = new HashSet<>();
private ListView listView;
private  ITransfer  iTransfer;

public MistakeGridFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.mistake_dialog, container, false);
    MistakeListHelper mistakeListHelper = new MistakeListHelper(getActivity());
    mistakeLists.addAll(mistakeListHelper.getAllMistakegrid());
    init(view);
    return view;
}

@TargetApi(23)
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        iTransfer = (ITransfer) context;
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

@Override
public void onAttach(Activity context) {
    super.onAttach(context);
    try {
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        iTransfer = (ITransfer) context;
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

private void init(View view) {
    relativeLayout = (LinearLayout) view.findViewById(R.id.mistakegrid_mainly);
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();

    // adding number of column
    for (int i = 0; i < mistakeLists.size(); i++) {
        String listvalue = mistakeLists.get(i).getListTypeValue();
        String name = mistakeLists.get(i).getListTypeName();
        Type type = new TypeToken<ArrayList<HashMap<Double, String>>>() {
        }.getType();
        ArrayList<HashMap<Double, String>> myMap = gson.fromJson(listvalue, type);
        for (int j = 0; j < myMap.size(); j++) {
            HashMap<Double, String> hash = myMap.get(j);
            view = setTypeOfMistake(name, hash, j);
        }
        relativeLayout.addView(view);
    }
}

private View setTypeOfMistake(final String mistakeName, HashMap<Double, String> hashValue, int i) {
    optionsArraylist = new ArrayList<>();
    //main mistake grid layout here added column
    LayoutInflater layoutInflatermain = LayoutInflater.from(getActivity());
    View main = layoutInflatermain.inflate(R.layout.mistake_column_layout, null);
    LinearLayout linearLayout = (LinearLayout) main.findViewById(R.id.linaerlayout);

    //here added row layout for each column
    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
    View view = layoutInflater.inflate(R.layout.mistake_row_layout, null);
    TextView mistakeType = (TextView) view.findViewById(R.id.header_tv);
    listView = (ListView) view.findViewById(R.id.listview);
    Set set = (Set) hashValue.entrySet();
    Iterator it = set.iterator();
    optionsArraylist.clear();

    while (it.hasNext()) {
        HashMap<Double, String> hashMap = new HashMap<>();
        Map.Entry entry = (Map.Entry) it.next();
        optionsArraylist.add((String) entry.getValue());
        hashMap.put((Double) entry.getKey(), (String) entry.getValue());
        mistakeHashArryList.add(hashMap);

    }

    mistakeType.setText(mistakeName + "");
    ArrayAdapter<String> adaptor = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, optionsArraylist);
    listView.setAdapter(adaptor);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

           toggleSelection(optionsArraylist.get(position).toString(), view);
            //Toast.makeText(QuestionActivity.this,parent.getItemAtPosition(position).toString(),Toast.LENGTH_SHORT).show();
            if (mistakeSelected.contains(parent.getItemAtPosition(position).toString())) {
                mistakeSelected.remove(parent.getItemAtPosition(position).toString());
                view.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.md_blue_grey_400));
            } else {
                mistakeSelected.add(parent.getItemAtPosition(position).toString());
                view.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.md_blue_grey_500));
            }
        }
    });

    linearLayout.addView(view);
    return linearLayout;
}

public boolean getMistake() {

    if (mistakeSelected.size() > 0) {

        iTransfer.getData(mistakeSelected);
        return true;
    } else {
        new MyUtils(getActivity()).setMessageShort("Please selected any one mistake");
    }
    return false;
}

public interface ITransfer {
  public  void getData(Set<String> strings);
}

public class MistakeReasonFragment extends Fragment implements MistakeGridFragment.ITransfer {
    private ArrayList<String> arrayList = new ArrayList<>();
    private TableLayout tableLayout;
    private LayoutInflater layoutInflater;
    private LinearLayout addMistake_row;
    public MistakeReasonFragment() {
    }





    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mistake_reason_layout, container, false);
        init(view);
        return view;
    }

    private void init(View view) {
        tableLayout = (TableLayout) view.findViewById(R.id.tablelayout);
        addMistake_row = (LinearLayout) view.findViewById(R.id.linaerl_row);
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }


    @Override
    public void getData(Set<String> strings) {
        Log.v("value size ", strings.size() + " ");
    }

}

logcat的:

  

java.lang.ClassCastException:com.android.root.ui.activity.QueActivity无法强制转换为com.tapasya.root.tapasya.ui.fragment.MistakeGridFragment $ ITransfer
  10-27 11:44:54.811 30409-30409 / com.tapasya.root.tapasya W / System.err:
  在com.android.root.ui.fragment.MistakeGridFragment.onAttach(MistakeGridFragment.java:70)
  10-27 11:44:54.811 30409-30409 / com.android.root W / System.err:
  在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1043)
  10-27 11:44:54.811 30409-30409 / com.android.root W / System.err:
  在android.support.v4.app.BackStackRecord.setLastIn(BackStackRecord.java:838)
  10-27 11:44:54.811 30409-30409 / com.android.root W / System.err:
  在android.support.v4.app.BackStackRecord.calculateFragments(BackStackRecord.java:861)

1 个答案:

答案 0 :(得分:0)

因为onAttach()中的上下文实例是片段的容器活动的实例,所以请确保容器活动已实现ITransfer回调,否则您无法在onAttach()中强制转换上下文对象的实例ITransfer参考变量。