0

I cannot get a toast to display in a fragment. I am using the PlacePicker, the user selects a place and the toast is supposed to show the place they selected. I have tried getContext(), getActivity().getApplicationContext() & getActivity() but none are working.

The PlacePicker is loading fine it just wont display the toast. I would also like to display the place the user has chosen in a TextView but the toast is the main priority.

My code is below:

public class Tab1 extends Fragment {

int PLACE_PICKER_REQUEST = 1;

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

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
    try {
        startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
    } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }

    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            Place place = PlacePicker.getPlace(data, getActivity());
            String toastMsg = String.format("Place: %s", place.getName());
            Toast.makeText(getContext(), toastMsg, Toast.LENGTH_LONG).show();
        }
    }
}
}
DToon12
  • 1
  • 5
  • `getActivity().startActivityForResult(...);` - Do not call that on the `Activity`. Just call it directly; i.e., remove `getActivity().` from that line - `startActivityForResult(...);`. – Mike M. Dec 04 '17 at 23:54
  • That fixed it, thanks. Do you know if there is a way to launch the place picker when the fragment is loaded instead of loading the place picker with a button and using the `onClick` method? – DToon12 Dec 05 '17 at 12:10
  • You can move that code - minus the `Button` stuff - to `onActivityCreated()`. – Mike M. Dec 05 '17 at 14:49
  • I have updated the code above to show what I have now. I have moved this to the `onActivityCreated()` but it still isn't appearing. Do I need to put something in the XML too? – DToon12 Dec 05 '17 at 15:49
  • Please don't change the actual question like that. It's fine that you asked a simple follow up in comments, but now this isn't what you originally asked. Anyway, I said `onActivityCreated()`, not `onActivityResult()`. – Mike M. Dec 05 '17 at 15:54
  • Ok thanks. I am new to stackoverflow and still trying to get used to the rules and ways of doing things. I will ask a new question in future if it is different to the original question. – DToon12 Dec 05 '17 at 16:06

0 Answers0