来自onPostExecute的ClusterManager.addItem null对象引用

时间:2016-03-18 08:46:20

标签: android json android-asynctask

sss我从json数组得到lat和lng但是当我尝试将它添加到我的集群时,我得到空对象引用

我的活动

 public class TabFragment2 extends Fragment implements OnMapReadyCallback {

    private static View rootView;
    public ClusterManager<MyItem> mClusterManager;
    private GetAsync  getAsync ;
    private boolean first = true;
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_Coordinates = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_X = "x_coordinate";
    private static final String TAG_Y = "y_coordinate";


    String type = "0";
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        Log.i("myMapFragment","onCreateView");

        if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null)
                parent.removeView(rootView);
            return rootView;
        }
        try {
            rootView = inflater.inflate(R.layout.tab_fragment_2, container, false);
        } catch (InflateException e) {
            /* map is already there, just return view as it is  */
        }

        SupportMapFragment mSupportMapFragment = (SupportMapFragment) this.getFragmentManager().findFragmentById(R.id.map);
            if (mSupportMapFragment == null) {
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                mSupportMapFragment = SupportMapFragment.newInstance();
                fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
            }
            if (mSupportMapFragment != null) {
                mSupportMapFragment.getMapAsync(this);

            }
        new GetAsync().execute(type);

        return rootView;

    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.i("myMapFragment","onActivityCreated");
        if (first){
            Log.i("if first","yes");
            getAsync  = new GetAsync ();
            getAsync.execute();
            first = false;
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.i("myMapFragment","onViewCreated");
    }



    public void onDestroyView() {
        super.onDestroyView();
        Log.i("myMapFragment", "onDestroyView");
    }



    @Override
    public void onMapReady(GoogleMap map) {
        LatLng sydney = new LatLng(-33.867, 151.206);


        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        map.setMyLocationEnabled(true);
        Log.i("on Map Ready", "yes");

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

        map.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.blue_pin))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(-33.867, 151.206)));

        setUpCluster(map);
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i("myMapFragment","onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("myMapFragment","onStop");
    }

    @Override
    public void onResume() {
        super.onResume();
        //initilizeMap();
        Log.i("myMapFragment","onResume");
    }

    private void setUpCluster(GoogleMap map){
        ClusterManager<MyItem> mClusterManager;
        // Initialize the manager with the context and the map.
        // (Activity extends context, so we can pass 'this' in the constructor.)
        mClusterManager = new ClusterManager<MyItem>(getActivity(),map);


        // Setting the custom render
        //mClusterManager.setRenderer(new MyClusterRenderer(getActivity(), googleMap, mClusterManager));

        // Point the map's listeners at the listeners implemented by the cluster manager.
        map.setOnCameraChangeListener(mClusterManager);
        map.setOnMarkerClickListener(mClusterManager);

        // Point the map's listeners at the listeners implemented by the cluster manager.
        mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<MyItem>() {
            @Override
            public boolean onClusterItemClick(MyItem offsetItem) {
                return false;
            }
        });
    }
    private class GetAsync extends AsyncTask<String, String, JSONArray> {

        JSONParser jsonParser = new JSONParser();

        private ProgressDialog pDialog;

        private static final String URL = "http://www.xxx.com.au/find/locations2.php";

        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

        //private Context context;

        // public GetAsync(Context context) {
        //     this.context = context;
        // }
        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(getContext());
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected JSONArray doInBackground(String... args) {

            try {

                HashMap<String, String> params = new HashMap<>();
                params.put("type", args[0]);

                Log.d("request", "starting");

                JSONObject json = jsonParser.makeHttpRequest(
                        URL, "GET", params);


                if (json != null) {
                    Log.d("JSON result", json.toString());

                    return json.getJSONArray(TAG_Coordinates);

                }
                else {
                    Log.d("JSON", "null");

                }

            } catch (Exception e) {
                Log.d("JSON", "ex");
            }

            return null;
        }
        //@Override
        protected void onPostExecute(JSONArray products) {

            String json_string;

            if (pDialog != null && pDialog.isShowing()) {
                pDialog.dismiss();
            }

            if (products != null) {
                json_string =  products.toString();
                Log.d("JSON onpost", json_string);
                for (int i = 0; i < products.length(); i++) {
                    Log.d("for", "yes");
                    JSONObject c = null;
                    try {
                        c = products.getJSONObject(i);
                        // Storing each json item in variable
                        int id = c.getInt(TAG_PID);
                        double lat = c.getDouble(TAG_X);
                        double lng = c.getDouble(TAG_Y);
                        Log.d("Lat", String.valueOf(lat));
                        Log.d("Lng", String.valueOf(lng));
                        MyItem offsetItem = new MyItem(lat, lng);


                        mClusterManager.addItem(offsetItem);

                    } catch (JSONException e) {
                        Toast.makeText(getActivity(), "Problem reading list of markers", Toast.LENGTH_SHORT).show();

                    }
                }
            }


        }

    }
    }

My Item.java

public class MyItem implements ClusterItem {
private final LatLng mPosition;

public MyItem(double lat, double lng) {
    mPosition = new LatLng(lat, lng);
}


@Override
public LatLng getPosition() {
    return mPosition;
}

}

logcat的

   03-18 03:59:24.621 19167-19167/com.joey.mapdemo D/JSON onpost:
 [{"pid":"2","x_coordinate":"-33.713165","y_coordinate":"151.297577"},{"pid":"5","x_coordinate":"-33.676090","y_coordinate":"151.302689"},{"pid":"6","x_coordinate":"-33.830978","y_coordinate":"151.205521"},{"pid":"7","x_coordinate":"-28.857418","y_coordinate":"153.560822"}]

    03-18 03:59:24.622 19167-19167/com.joey.mapdemo D/for: yes
     03-18 03:59:24.625 19167-19167/com.joey.mapdemo D/Lat: -33.713165
     03-18 03:59:24.625 19167-19167/com.joey.mapdemo D/Lng: 151.297577

     03-18 03:59:24.686 19167-19167/com.joey.mapdemo D/AndroidRuntime: Shutting down VM
     03-18 03:59:24.702 19167-19167/com.joey.mapdemo E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.joey.mapdemo, PID: 19167
     java.lang.NullPointerException: Attempt to invoke virtual method 'void
 com.google.maps.android.clustering.ClusterManager.addItem(com.google.maps.android.clustering.ClusterItem)'
 on a null object reference

     at com.joey.mapdemo.TabFragment2$GetAsync.onPostExecute(TabFragment2.java:267)
     at com.joey.mapdemo.TabFragment2$GetAsync.onPostExecute(TabFragment2.java:185)

0 个答案:

没有答案