MapView not loading when going back to dialog (MapBox)

104
January 11, 2018, at 03:04 AM

Within a fragment, I create a dialog which contains a MapView (MapBox). This loads great and all. The dialog redirects the user (when the user clicks on a button) to another Activity. When the user presses back in that Activity (to go to the dialog), the MapView simply doesn't load anymore, until it gets pressed. I am using MapBox's implementation of the MapView.

I tried implementing the onPause, onResume, onLowMemory and onDestroy methods, by calling their respective methods in MapView, but that way the MapView does not load at all, not even when I click on it.

The fragment for an adapter:

public class DayAdapter extends FragmentStatePagerAdapter {
/**
 * Construct the fragment pager adapter.
 * @param fragmentManager The manager
 */
public DayAdapter(final FragmentManager fragmentManager) {
    super(fragmentManager);
}
/**
 * Gets the Fragment to be rendered at <i>position</i>.
 * @param position The position of the item.
 * @return Fragment The Fragment that has to be rendered.
 */
@Override
public Fragment getItem(int position) {
    Fragment fragment = new DayFragment();
    Bundle args = new Bundle();
    args.putInt(DayFragment.ARG_OBJECT, position);
    fragment.setArguments(args);
    return fragment;
}
/**
 * Gets the total count of items.
 * @return Integer The amount of items.
 */
@Override
public int getCount() {
    return 100;
}
/**
 * Fragment to display the Day.
 */
public static class DayFragment extends Fragment {
    public static final String ARG_OBJECT = "object";
    private final Client client = Client.getInstance();
    private WorkorderDialog d;
    /**
     * Constructs the Day view.
     * @param inflater The inflater for the Fragment.
     * @param container The container of the Fragment.
     * @param savedInstanceState The arguments of the saved state.
     * @return View The view of the day.
     */
    @Override
    public View onCreateView(final LayoutInflater inflater,
                             final ViewGroup container, final Bundle savedInstanceState) {
        final View rootView = inflater.inflate(
                R.layout.day_fragment, container, false);
        final Bundle args = getArguments();
        final int dayPosition = args.getInt(ARG_OBJECT);
        final int deviation = dayPosition - 50;
        final Date devDate = DateUtil.getDateFromNow(deviation);
        final String renderedDate = DateUtil.getDayInWeek(devDate) + " "
                + DateUtil.getDayOfMonth(devDate) + " "
                + DateUtil.getMonth(devDate);
        ((TextView) rootView.findViewById(R.id.date)).setText(renderedDate);
        final String currentDate = new SimpleDateFormat("MM/dd/yyyy").format(devDate);
        final JSONArray workOrders = client.getWorkOrders(currentDate);
        final ListView jobList = (ListView) rootView.findViewById(R.id.jobList);
        jobList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    d = new WorkorderDialog(client.getCurrentActivity(), workOrders.getJSONObject(i), renderedDate, savedInstanceState);
                    d.constructDialog();
                    d.show();
                } catch (JSONException e) {
                    Log.e("CrafterException", e.getMessage());
                }
            }
        });
        jobList.setEmptyView(rootView.findViewById(R.id.emptyTextView));
        jobList.setAdapter(new JobAdapter(workOrders, inflater));
        return rootView;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (d != null) {
            d.onResume();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        if (d != null) {
            d.onResume();
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        if (d != null) {
            d.onPause();
        }
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (d != null) {
            d.onLowMemory();
        }
    }
}

The Dialog:

public class WorkorderDialog extends Dialog {
private final JSONObject selectedOrder;
private final MapView googleMap;
private final Client client = Client.getInstance();
private final String renderedDate;
private final Bundle savedInstanceState;
private final Context context;
public WorkorderDialog(final @NonNull Context context, final JSONObject workorder, final String renderedDate, final Bundle savedInstanceState) {
    super(context);
    setContentView(R.layout.workorder_dialog);
    this.context = context;
    this.selectedOrder = workorder;
    this.renderedDate = renderedDate;
    this.savedInstanceState = savedInstanceState;
    this.googleMap = (MapView) findViewById(R.id.locationMap);
}
public void constructDialog() {
    final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    getWindow().setAttributes(lp);
    try {
        final String startTime = new SimpleDateFormat("HH.mm").format(new Date(selectedOrder.getLong("start_time") * 1000L));
        final String endTime = new SimpleDateFormat("HH.mm").format(new Date(selectedOrder.getLong("end_time") * 1000L));
        final String essentialInfo = renderedDate + " - " + startTime + " - " + endTime;
        final String title = selectedOrder.getJSONObject("client").getString("company");
        final String description = selectedOrder.getString("description");
        final String materials = JSONArrayUtil.sumProperty(selectedOrder.getJSONArray("materials"), "amount") + " materialen mee te nemen";
        final JSONObject address = selectedOrder.getJSONObject("location").getJSONObject("adress");
        final JSONObject contact = selectedOrder.getJSONObject("location").getJSONObject("contactperson");
        final String locationNotes = address.has("notes") ?
                ("".equals(address.getString("notes")) || "null".equals(address.getString("notes")) ?
                        "Geen locatie beschrijving" : address.getString("notes")) : "Geen locatie beschrijving";
        final String location = locationNotes + "\n" +
                address.getString("street") + " " +
                address.getString("number") + ", " +
                address.getString("city");
        final String contactPerson = contact.getString("first_name") + " " +
                contact.getString("last_name") + "\n" +
                contact.getString("phone");
        ((TextView) findViewById(R.id.dialogTitle)).setText(title);
        ((TextView) findViewById(R.id.locationText)).setText(location);
        ((TextView) findViewById(R.id.contactText)).setText(contactPerson);
        ((TextView) findViewById(R.id.dialogInfo)).setText(essentialInfo);
        ((TextView) findViewById(R.id.descriptionText)).setText(description);
        ((TextView) findViewById(R.id.materialsText)).setText(materials);
        (findViewById(R.id.closeDialogButton)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        if (!selectedOrder.has("localStatus") || (selectedOrder.has("localStatus") && selectedOrder.getInt("localStatus") != 3)) {
            (findViewById(R.id.openWorkOrder)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent openWorkOrder = new Intent(client.getCurrentActivity(), WorkOrderActivity.class);
                    final Bundle passedArguments = new Bundle();
                    try {
                        if (!selectedOrder.has("localStatus")) {
                            selectedOrder.put("localStatus", 1);
                        }
                        WorkOrderHandler.getInstance().setEditingWorkOrder(selectedOrder);
                    } catch (JSONException e) {
                        Log.e("CrafterException", e.getMessage());
                    }
                    passedArguments.putString("workorder", selectedOrder.toString());
                    openWorkOrder.putExtras(passedArguments);
                    client.getCurrentActivity().startActivity(openWorkOrder);
                }
            });
        } else {
            ((ImageView) findViewById(R.id.openWorkOrder)).setImageResource(R.drawable.button_closed_workorder);
        }
        Mapbox.getInstance(getContext(), "pk.eyJ1IjoibWV0YWhleGFuZSIsImEiOiJjamFtYXE1Z3M0YmhoMndwN2lqZWp3aG91In0.VJrwxikM6yhPobgM59gl4g");
        googleMap.onCreate(savedInstanceState);
        if (!(address.get("lat") instanceof  String) && !(address.get("lng") instanceof String)) {
            final double lat = address.getDouble("lat");
            final double lng = address.getDouble("lng");
            googleMap.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(MapboxMap mapboxMap) {
                    mapboxMap.addMarker(new MarkerOptions()
                            .position(new LatLng(lat, lng))
                            .icon(IconFactory.getInstance(getContext()).fromResource(R.drawable.ic_map)));
                    mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
                    mapboxMap.getUiSettings().setScrollGesturesEnabled(false);
                    mapboxMap.getUiSettings().setDoubleTapGesturesEnabled(false);
                    googleMap.onResume();
                }
            });
        }
        findViewById(R.id.constraintLayout10).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = null;
                try {
                    intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://www.google.com/maps/dir/?api=1&destination=" + address.getString("street") + "+" + address.getString("number") + "+" + address.getString("city")));
                    context.startActivity(intent);
                } catch (JSONException e) {
                    Log.e("CrafterException", e.getMessage());
                }
            }
        });
    } catch (JSONException e) {
        Log.e("CrafterException", e.getMessage());
    }
}
@Override
protected void onStart() {
    super.onStart();
    if (googleMap != null) googleMap.onStart();
}
@Override
protected void onStop() {
    super.onStop();
    if (googleMap != null) googleMap.onStop();
}
@Override
public void dismiss() {
    super.dismiss();
    if (googleMap != null) googleMap.onDestroy();
}
public void onResume() {
    if (googleMap != null) googleMap.onResume();
}
public void onPause() {
    if (googleMap != null) googleMap.onPause();
}
public void onLowMemory() {
    if (googleMap != null) googleMap.onLowMemory();
}
Answer 1

In a Fragment implementation of the MapView you need to call MapView#onDestroy in Fragement#onDestroyView like so:

@Override
public void onDestroyView() {
  super.onDestroyView();
  mapView.onDestroy();
}

This ensures the MapView is properly shutdown so it can be used again when you show the dialog a second time. Hopefully this helps!

READ ALSO
Exception : org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class

Exception : org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class

Below all are my filesWhen I try to implement a one to many and a many to one relation between the tables I am getting an AnnotationException

179
How to make a shape move to click in JPanel?

How to make a shape move to click in JPanel?

I am trying to make to make a shape move to wherever I click my mouseI got the shape to move, and it moves towards the general direction of where I clicked, but it never moves exactly to where I clicked, it misses by a good distance

129
JSCIPOpt set objective

JSCIPOpt set objective

I am trying to use JSCIPOpt to solve a maximization problem but I couldn't find a way to set the problem objectiveThe scip document says

104
Java - Setting values in ArrayList with changing variables modify values of ArrayList

Java - Setting values in ArrayList with changing variables modify values of ArrayList

I'm facing a problem using ArrayListI'm using an ArrayList with this content :

136