获取ArrayList坐标时出错

时间:2017-07-04 19:16:45

标签: java android arraylist

我一直试图解决这个问题已经有一个星期了,我已经尝试过这些问题而且我已经做了一些测试,但是我还没有找到解决这个问题的方法。

Java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.Object java.util.ArrayList.get(int)'

它表示这一行:

Latitude = Double.parseDouble (location.get (i) .get ("Latitude"). ToString ());

Print Error 完整代码:

public class TabFragment2 extends Fragment {

    private IFragmentToActivity mCallback;
    MapView mMapView;
    private GoogleMap googleMap;


    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.tab_fragment_2, container,
                false);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "https://192.168.0.1/geo.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                map.put("Tipo", c.getString("Tipo"));
                location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        // *** Display Google Map
        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            String tipo = location.get(i).get("Tipo").toString();
            MarkerOptions marker = new MarkerOptions()
                    .position(new LatLng(Latitude, Longitude)).title(name);
            if(tipo.equals("CORTE")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }
            if(tipo.equals("RELIGACAO")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }
            if(tipo.equals("VISTORIA")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }
            googleMap.addMarker(marker);
        }

        return v;
    }



    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();

    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 2: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    public void fragmentCommunication() {
        // mTextView1.setText("Hello from Tab Fragment 1");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}

代码json:

[{"LocationID":"19637099","Latitude":" -5.080922","Longitude":"-42.816135","LocationName":"10032576","Tipo":"RELIGACAO"},{"LocationID":"19659563","Latitude":" -5.085750","Longitude":"-42.813892","LocationName":"518620","Tipo":"RELIGACAO"}]

2 个答案:

答案 0 :(得分:0)

我想如果try / catch语句捕获错误,那么你的位置ArrayList实际上可能是null。所以试着看看是否会发生这种情况以及如何避免它。

public StateHolderSaver(FacesContext context, Object toSave){
   this.className=toSave!=null?toSave.getClass().getName():null;

答案 1 :(得分:0)

也许你应该在以下情况下使用这个条件:

if(location.get(i)!= null)