0

I got a problem with how to update fragment within dialog fragment.

here is an image of my application: it is my application

when I click of the filter menu button a new dialog fragment is shown which includes a radio group.

dialog

I want to update the fragment that contains a list of places when I clicked the ok button.

it is a code of PlaceActivity which contains the PlaceFragment:

public class PlaceActivity extends AppCompatActivity {

// assign frame layout.
FrameLayout frameLayout;
// assign bottom navigation.
BottomNavigationView bottomNavigationView;

//assign and initialize whole of fragments.
FavoriteFragment favoriteFragment = new FavoriteFragment();
MyPlanFragment myPlanFragment = new MyPlanFragment();
PlaceFragment placeFragment = new PlaceFragment();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.place_activity);

    // initialize views by id.
    frameLayout = findViewById(R.id.frame_place_activity);
    bottomNavigationView = findViewById(R.id.bottom_navigation_view);


    // Set book fragment as initial fragment.
    setFragment(placeFragment);
    bottomNavigationView.setSelectedItemId(R.id.bottom_nav_place);

    // Set on click listener on bottom navigation items.
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            switch (menuItem.getItemId()){
                case R.id.bottom_nav_plan:
                    setFragment(myPlanFragment);
                    return true;
                case R.id.bottom_nav_place:
                    setFragment(placeFragment);
                    return true;
                case R.id.bottom_nav_favorite:
                    setFragment(favoriteFragment);
                    return true;
                default:
                    return false;
            }
        }
    });

}


/**
 * set frame layout to the fragment of argument.
 * @param fragment is used in order to inflate frame layout.
 */
private void setFragment(Fragment fragment) {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame_place_activity,fragment);
    fragmentTransaction.commit();
}

}

Here is the code of PlaceFragment class:

public class PlaceFragment extends Fragment{

public static final String TAG = PlaceFragment.class.getName();

// String which stores json string returnable.
String jsonResponse = GooglePlaceJson.MALLS_JSON_RESPONSE;

// Shared Preferences is used to return back the id of selected item.
SharedPreferences sharedPreference;

// Empty view is shown when the list view does not contain any items.
TextView emptyView;

public PlaceFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_place, container, false);
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    super.onCreate(savedInstanceState);
}

// called when view is created.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    //ListView for showing a list of places
    ListView listView = view.findViewById(R.id.list);

    //TextView for showing a empty list view.
    emptyView = view.findViewById(R.id.empty_text_view);

    //Create an object of QueryUtils in order to get data from it.
    QueryUtils queryUtils = new QueryUtils(jsonResponse);

    //Adding a list of the places.
    ArrayList<Place> places = queryUtils.extractPlaces();

    //Array adapter used to get the source data and the layout of the list item.
    final PlaceAdapter placeAdapter = new PlaceAdapter(getContext(), places);

    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    listView.setAdapter(placeAdapter);

    // Set the empty view to list view, cause it will show when there is not item on the list view.
    listView.setEmptyView(emptyView);

    // Set clickable method on item list view.
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // Find the current place that was clicked on
            Place currentPlace = placeAdapter.getItem(position);

            // Intent used to go to second activity.
            Intent goPlaceDetail = new Intent(getContext(), DetailedPlace.class);
            // Pass current Activity to another Activity.
            goPlaceDetail.putExtra("currentPlace",currentPlace);
            startActivity(goPlaceDetail);
        }
    });

}

// Create a menu then add it to the fragment.
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
    inflater.inflate(R.menu.main_menu,menu);
}

// Set on click listener on the menu items.
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.place_menu_filter_:
            // Assign shared preference.
            sharedPreference= getContext().getSharedPreferences(ExampleDialog.MY_PREFS_NAME,MODE_PRIVATE);
            // Open dialog to filter places.
            openDialog();
            // Get the checked text
            String checkedTextItem = sharedPreference.getString(ExampleDialog.CHECKED_ITEM_TEXT_KEY,"");
            if (checkedTextItem.equals(ExampleDialog.RESTAURANT)){
                jsonResponse = GooglePlaceJson.RESTAURANT_JSON_RESPONSE;
            } else if(checkedTextItem.equals(ExampleDialog.MALL)){
                jsonResponse = GooglePlaceJson.MALLS_JSON_RESPONSE;
            }

            this.onViewCreated(getView().findViewById(R.id.list),null);
            return true;
        case R.id.action_settings:
            // Go settings activity when the settings menu item was clicked.
            Intent goSettings = new Intent(getContext(), SettingsActivity.class);
            // Start activity to go to second activity.
            startActivity(goSettings);
            return true;
        default:
            return false;
    }
}


/**
 * Method is used to open dialog.
 */
private void openDialog() {
    // Create an object of the custom dialog.
    ExampleDialog exampleDialog = new ExampleDialog();
    exampleDialog.show(getFragmentManager(),"filter place dialog");

}

}

Here is the code of ExampleDialog class:

public class ExampleDialog extends AppCompatDialogFragment {

// key of shared preference.
public static final String MY_PREFS_NAME =  "dialog_preference";
public static final String CHECKED_ITME_KEY = "checked_item_key";
public static final String CHECKED_ITEM_TEXT_KEY= "checked_item_text_key";


// Place whole returned possible values.
public static final String RESTAURANT = "restaurant";
public static final String MALL = "mall";
public static final String PARK = "park";


// Declare radio button and button groups.
private static RadioGroup radioGroup;
private static RadioButton restaurant,mall,park;





//Created shared Preference editor in order to add data from it.
SharedPreferences.Editor editor;

//Created shared Preference in order to get data from it.
SharedPreferences sharedPreferences;

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    // Create an alert dialog builder to build an dialog.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    // Use layout inflater in order to add resource to our application.
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialog_fragment,null);

    // Assign views with find view by id.
    radioGroup = view.findViewById(R.id.place_radio_group);

    mall = view.findViewById(R.id.mall_radio_button);
    restaurant = view.findViewById(R.id.restaurant_radio_button);
    park = view.findViewById(R.id.park_radio_button);

    // Shared preference is used to get data if it is available.
    sharedPreferences = getActivity().getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);

    // Get the checked item from application.
    int selectedId = sharedPreferences.getInt(CHECKED_ITME_KEY,0);
    if (selectedId !=0){
        radioGroup.check(selectedId);
    }else {
        radioGroup.check(restaurant.getId());
    };

    // Create shared preference editor in order to set data into shared preference.
    editor = getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();


    // Add cancel and ok buttons on the dialog and set it onclick listener.
    builder.setView(view)
            .setTitle(getString(R.string.msg_radio_group))
            .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    // Get id of whole button in order to return a right data.
                    int restaurantId = restaurant.getId();
                    int mallId = mall.getId();
                    int parkId = park.getId();

                    // Get checked button id of radio group.
                    int checkedId = radioGroup.getCheckedRadioButtonId();
                    // Put checked it of radio button on shared preference.
                    editor.putInt(CHECKED_ITME_KEY,checkedId);

                    // Put text of checked item into shared preference.
                    if (checkedId == restaurantId){
                        editor.putString(CHECKED_ITEM_TEXT_KEY,RESTAURANT);
                    }else if (checkedId == mallId){
                        editor.putString(CHECKED_ITEM_TEXT_KEY,MALL);
                    }else if(checkedId == parkId){
                        editor.putString(CHECKED_ITEM_TEXT_KEY,PARK);

                    }
                    editor.apply();
                    radioGroup.check(checkedId);

                }
            });


    // Create dialog.
    return builder.create();
}


public interface ExampleDialogListener{
    void applyTexts();
}

}

1 Answers1

0

Just before calling exampleDialog.show(getFragmentManager(),"filter place dialog"); call

exampleDialog.setTargetFragment( PlaceFragment.this, MY_DATA_REQUEST_CODE)

then in the ExampleDialog class just after getting data from the radio button in the onClick() method, put the data as an extra in an intent maybe called intentWithDialogData, then call getTargetFragment().onActivityResult(MY_DATA_REQUEST_CODE, RESULT_CODE, intentWithDialogData), override onActivityResult() in calling fragment (PlaceFragment) to receive data from passed intent

  • Hey, bro! can you explain more? – Muhamad Haydar Jawad Apr 21 '20 at 00:10
  • After initialising the ExampleDialog object, you can set a target fragment to pass data to (as long as they are attached to the same activity) via an intent by using Fragment class inherited function; `exampleDialog.setTargetFragment(fragment, REQUEST CODE)`, then inside the DialogFragment (ExampleDialog class), call `getTargetFragment().onActivityResult(int requestCode, int resultCode, Intent data)` in your buttonclick listener, pass your desired integer request code, RESULT_OK, and an intent with the data you want to send. Then in the PlaceFragment handle onActivityResult(). Get it now? – ADEBAYO OSIPITAN Apr 21 '20 at 19:13
  • See this reference: https://stackoverflow.com/questions/18561119/android-gettargetfragment-and-settargetfragment-what-are-they-used-for – ADEBAYO OSIPITAN Apr 21 '20 at 19:15