• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Passing data between two fragments

Hello guys,

I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:

Code:
public class CourseListFragment extends Fragment implements
		OnItemClickListener, OnItemLongClickListener {

	public static final String ARG_ITEM_ID = "course_list";
	public static final String YES_NO = "modify";

	Activity activity;
	ListView courseListView;
	ArrayList<Course> courses;

	CourseListAdapter courseListAdapter;
	CourseDAO courseDAO;

	private GetEmpTask task;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity = getActivity();
		courseDAO = new CourseDAO(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.schedule_fragment_course_list,
				container, false);
		findViewsById(view);

		task = new GetEmpTask(activity);
		task.execute((Void) null);

		courseListView.setOnItemClickListener(this);
		courseListView.setOnItemLongClickListener(this);
		return view;
	}

	private void findViewsById(View view) {
		courseListView = (ListView) view.findViewById(R.id.list_course);
	}

	@Override
	public void onItemClick(AdapterView<?> list, View view, int position,
			long id) {
		Course course = (Course) list.getItemAtPosition(position);

		if (course != null) {
			Bundle arguments = new Bundle();
			arguments.putParcelable("selectedCourse", course);
			CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
			customEmpDialogFragment.setArguments(arguments);
			customEmpDialogFragment.show(getFragmentManager(),
					CustomCourseDialogFragment.ARG_ITEM_ID);
		}
	}

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

		// Show dialogFragment
		FragmentManager fm = getActivity().getSupportFragmentManager();
		CheckDialogFragment dialog = new CheckDialogFragment();
		dialog.show(fm, YES_NO);

		Course employee = (Course) parent.getItemAtPosition(position);
		// Use AsyncTask to delete from database
		courseDAO.deleteEmployee(employee);
		courseListAdapter.remove(employee);

		return true;
	}

	public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {

		private final WeakReference<Activity> activityWeakRef;

		public GetEmpTask(Activity context) {
			this.activityWeakRef = new WeakReference<Activity>(context);
		}

		@Override
		protected ArrayList<Course> doInBackground(Void... arg0) {
			ArrayList<Course> courseList = courseDAO.getCourses();
			return courseList;
		}

		@Override
		protected void onPostExecute(ArrayList<Course> empList) {
			if (activityWeakRef.get() != null
					&& !activityWeakRef.get().isFinishing()) {
				courses = empList;
				if (empList != null) {
					if (empList.size() != 0) {
						courseListAdapter = new CourseListAdapter(activity,
								empList);
						courseListView.setAdapter(courseListAdapter);
					} else {
						Toast.makeText(activity, "No Course Records",
								Toast.LENGTH_LONG).show();
					}
				}
			}
		}
	}

	/*
	 * This method is invoked from MainActivity onFinishDialog() method. It is
	 * called from CustomEmpDialogFragment when an employee record is updated.
	 * This is used for communicating between fragments.
	 */
	public void updateView() {
		task = new GetEmpTask(activity);
		task.execute((Void) null);
	}

	@Override
	public void onResume() {
		getActivity().setTitle("Course Schedule");
		getActivity().getActionBar().setTitle("Course Schedule");
		super.onResume();
	}
}



//Dialog Fragment

Code:
public class CheckDialogFragment extends DialogFragment {
	
	CourseListAdapter courseListAdapter;
	CourseDAO courseDAO;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
				.setTitle("Do you want to delete?")
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							}
						});
		return builder.create();
	}
}

I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.
 
Well, from CourseListFragment to CheckDialogFragment, must be easy, because you are creating the latter in the former. If you want to send data the other way around, then the parent Activity is your answer. The activity must handle the data that you want to share between the child fragments.
 
The best way you can learn this is to see an example. Here is an example I put together for you. If you have any questions, please don't hesitate! :)

Yes / No DialogFragment with Listener Example:

QuestionDialogFragment

Code:
public final class QuestionDialogFragment extends DialogFragment {
    private static final String TAG = QuestionDialogFragment.class.getSimpleName();

    private static final String BUNDLE_TITLE = "title";
    private static final String BUNDLE_MESSAGE = "message";
    private static final String BUNDLE_POSITIVE_BUTTON_TEXT = "positiveButtonText";
    private static final String BUNDLE_NEGATIVE_BUTTON_TEXT = "negativeButtonText";

    private OnClickListener mPositiveOnClickListener;
    private OnClickListener mNegativeOnClickListener;

    private static QuestionDialogFragment newInstance(String title, String message,
            String positiveButtonText, OnClickListener positiveOnClickListener,
            String negativeButtonText, OnClickListener negativeOnClickListener) {
        QuestionDialogFragment dialogFragment = new QuestionDialogFragment();

        Bundle args = new Bundle();
        args.putString(BUNDLE_TITLE, title);
        args.putString(BUNDLE_MESSAGE, message);
        args.putString(BUNDLE_POSITIVE_BUTTON_TEXT, positiveButtonText);
        args.putString(BUNDLE_NEGATIVE_BUTTON_TEXT, negativeButtonText);
        dialogFragment.setArguments(args);
        dialogFragment.mPositiveOnClickListener = positiveOnClickListener;
        dialogFragment.mNegativeOnClickListener = negativeOnClickListener;
        return dialogFragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle args = getArguments();
        Builder b = new Builder(getActivity(), AlertDialog.THEME_HOLO_DARK);
        b.setTitle(args.getString(BUNDLE_TITLE));
        b.setMessage(args.getString(BUNDLE_MESSAGE));
        b.setIcon(android.R.drawable.ic_dialog_alert);
        setCancelable(false);
        b.setPositiveButton(args.getString(BUNDLE_POSITIVE_BUTTON_TEXT), mPositiveOnClickListener);
        if (mNegativeOnClickListener != null) {
            b.setNegativeButton(args.getString(BUNDLE_NEGATIVE_BUTTON_TEXT), mNegativeOnClickListener);
        }
        return b.create();
    }

    public static class QuestionDialogFragmentBuilder {

        private FragmentActivity mActivity;
        private String mTitle;
        private String mMessage;
        private String mPositiveButtonText;
        private OnClickListener mPositiveButtonOnClickListener;
        private String mNegativeButtonText;
        private OnClickListener mNegativeButtonOnClickListener;

        public QuestionDialogFragmentBuilder(FragmentActivity activity) {
            mActivity = activity;
            mPositiveButtonText = activity.getString(android.R.string.yes);
            mNegativeButtonText = activity.getString(android.R.string.no);
        }

        public QuestionDialogFragmentBuilder setTitle(int resId) {
            mTitle = mActivity.getString(resId);
            return this;
        }

        public QuestionDialogFragmentBuilder setTitle(String text) {
            mTitle = text;
            return this;
        }

        public QuestionDialogFragmentBuilder setMessage(int resId) {
            mMessage = mActivity.getString(resId);
            return this;
        }

        public QuestionDialogFragmentBuilder setMessage(String text) {
            mMessage = text;
            return this;
        }

        public QuestionDialogFragmentBuilder setPositiveButton(int resId,
                OnClickListener onClickListener) {
            return setPositiveButton(mActivity.getString(resId), onClickListener);
        }

        public QuestionDialogFragmentBuilder setPositiveButton(String text,
                OnClickListener onClickListener) {
            mPositiveButtonText = text;
            mPositiveButtonOnClickListener = onClickListener;
            return this;
        }

        public QuestionDialogFragmentBuilder setNegativeButton(int resId,
                OnClickListener onClickListener) {
            return setNegativeButton(mActivity.getString(resId), onClickListener);
        }

        public QuestionDialogFragmentBuilder setNegativeButton(String text,
                OnClickListener onClickListener) {
            mNegativeButtonText = text;
            mNegativeButtonOnClickListener = onClickListener;
            return this;
        }

        public void show() {
            FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            Fragment prev = fragmentManager.findFragmentByTag(TAG);
            if (prev != null) {
                fragmentTransaction.remove(prev);
            }
            fragmentTransaction.addToBackStack(null);

            QuestionDialogFragment.newInstance(mTitle, mMessage, mPositiveButtonText,
                    mPositiveButtonOnClickListener, mNegativeButtonText,
                    mNegativeButtonOnClickListener).show(fragmentManager, TAG);
        }

    }

    public static void dismiss(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        Fragment prev = fragmentManager.findFragmentByTag(TAG);
        if (prev != null) {
            fragmentTransaction.remove(prev);
        }
        fragmentTransaction.commit();
    }
}

Creating the DialogFragment from the main fragment
Code:
QuestionDialogFragment.QuestionDialogFragmentBuilder b =
            new QuestionDialogFragment.QuestionDialogFragmentBuilder(baseActivity);
    b.setTitle(context.getString(R.string.title));
    b.setMessage(context.getString(R.string.message));
    b.setPositiveButton(android.R.string.yes, dialogListener);
    b.setNegativeButton(android.R.string.no, dialogListener);
    b.show();

public DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int which) {
        if (which == DialogInterface.BUTTON_POSITIVE) {
            dialogInterface.dismiss();
            // ... your code here ...
        }
        dialogInterface.dismiss();
    }
};
 
Back
Top Bottom