当Activity首次运行时,为什么我收到错误“numberFormatException:empty string”?

时间:2017-12-14 18:07:34

标签: android android-mapview

所以当Activity首次运行并且应用程序崩溃时我不断收到错误。当我重新打开应用程序时,代码运行良好而没有错误...我猜我的代码试图将String转换为Double之前'Lng + Lat'字符串实际上包含一个值(在用户定位之前)。如何防止此问题发生(不使用字符串中的虚拟数据)?请参阅下面的代码。错误发生在第326行。

public class nearMe extends AppCompatActivity implements OnMapReadyCallback {

    private MapView mapView;
    public GoogleMap gmap;
    private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";

    ActionBar actionBar;
    LocationManager locationManager;
    LocationListener locationListener;

    private List<Station> stationList = new ArrayList<>();
    private RecyclerView recyclerView;
    private stationAdapter mAdapter;

    /*   LOCATION STUFF     */
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                startListening();

            }
        }
    }

    public void startListening() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            updateMap();


        }
    }
    // Dummy Location Co-ordinates - Covent garden
    private String lat = "";
    private String lng = "";

    public void updateLocationInfo(Location location) {
        lat = "" + location.getLatitude();
        lng = "" + location.getLongitude();
    }

    //BUTTON TO UPDATE LOCATION IN ACTIONBAR
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_location, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        getNearestStations();
        updateMap();
        Toast.makeText(this, "Location Updated!", Toast.LENGTH_SHORT).show();
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_me);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);


        actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4c4c4c")));
        actionBar.setTitle("Nearest Stations");


        mAdapter = new stationAdapter(stationList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

// onClick
        recyclerView.addOnItemTouchListener(new TouchListener(getApplicationContext(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                // Toast.makeText(getApplicationContext(), stationList.get(position).getStation() + "", Toast.LENGTH_SHORT).show();

                String findStation = stationList.get(position).getStation();

                Uri gmmIntentUri = Uri.parse("google.navigation:q="+findStation+"underground station+London&mode=w");
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                mapIntent.setPackage("com.google.android.apps.maps");
                mapIntent.setFlags(mapIntent.FLAG_ACTIVITY_CLEAR_TOP);
                if (mapIntent.resolveActivity(getPackageManager()) != null) {
                    startActivity(mapIntent);
                }
            }
        }));

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateLocationInfo(location);


            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
// PERMISSIONS CHECK FOR MARSHMALLOW AND LATER!
        if (Build.VERSION.SDK_INT < 23) {
            startListening();
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                if (location != null) {
                    updateLocationInfo(location);
                }
            }
        }

        // insert Stations in to recycler
        getNearestStations();

        //map
        Bundle mapViewBundle = null;
        if (savedInstanceState != null) {
            mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
        }

        mapView = (MapView) findViewById(R.id.map_view);
        mapView.onCreate(mapViewBundle);
        mapView.getMapAsync(this);
    }

    // clear adapter before adding
    public void clear() {
        int size = this.stationList.size();
        this.stationList.clear();
        mAdapter.notifyItemRangeRemoved(0, size);
    }

    public void getNearestStations(){

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=157c4895&app_key=091697cea8bae89519dd02ebb318fc51&lat=" + lat + "&lon=" + lng + "&rpp=5";

        final StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("stations");

                    // Call 'Clear' method to clear mAdapter before adding new data
                    clear();
                    if (jsonArray.length() > 0) {

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jObject = jsonArray.getJSONObject(i);

                            String station = jObject.getString("name");

                            Station newStation = new Station(station);
                            stationList.add(newStation);

                            mAdapter.notifyDataSetChanged();
                        }
                    }else{
                        Station newStation = new Station("No stations near");
                        stationList.add(newStation);
                        mAdapter.notifyDataSetChanged();

                        // Show a diaog
                        AlertDialog alertDialog = new AlertDialog.Builder(nearMe.this).create();
                        alertDialog.setTitle("No Stations Found");
                        alertDialog.setMessage("You are either not in London or you have no network connectivity.");
                        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }); alertDialog.show();
                    }
                } catch (JSONException e) { }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }
// maps

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
        if (mapViewBundle == null) {
            mapViewBundle = new Bundle();
            outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
        }
        mapView.onSaveInstanceState(mapViewBundle);
    }
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }
    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        gmap = googleMap;
        updateMap();
    }


    public void updateMap () {

        double longitude = Double.parseDouble(lng);
         double latitude  = Double.parseDouble(lat);
        gmap.clear();

        gmap.setMinZoomPreference(12);
        LatLng ldn = new LatLng(latitude, longitude);
        gmap.moveCamera(CameraUpdateFactory.newLatLng(ldn));
        gmap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mapmarker)));
    }
}

0 个答案:

没有答案
相关问题