如何删除NumberFormat异常?

时间:2016-10-17 04:05:52

标签: java android numberformatexception

我的第一项活动是这样的:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

GoogleMap mMap;
LocationManager locationManager;
TextView tvStartRide, tvEndRide;
FloatingActionButton fabRate, fabLocation;
double start_latitude, start_longitude;
double end_latitude, end_longitude;
long start_time, end_time;
float baseRate, rate;
float distance;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);



    //Getting BaseRate and Rate from SetFareActivity
   /** Bundle bundle = this.getIntent().getExtras();
    if(bundle!=null) {
        BaseRate = bundle.getString("baseRate");
        Rate =bundle.getString("rate");

        baseRate=Float.parseFloat(BaseRate);
        rate=Float.parseFloat(Rate);
    }
    else
        Toast.makeText(getApplicationContext(),"Nothing Recieved",Toast.LENGTH_SHORT).show(); **/

    //start ride Methods


    tvStartRide = (TextView) findViewById(R.id.tvStartRide);
    tvStartRide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager)
                    getSystemService(LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    Activity#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 Activity#requestPermissions for more details.
                    return;
                }
            }
            Location location = locationManager.getLastKnownLocation(bestProvider);
            start_latitude = location.getLatitude();
            start_longitude = location.getLongitude();
            start_time = System.currentTimeMillis();

            LatLng latLng = new LatLng(start_latitude, start_longitude);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
            markerOptions.position(latLng);
            mMap.addMarker(new MarkerOptions().position(latLng).title("Start Point").draggable(true));
            tvStartRide.setVisibility(View.GONE);
            tvEndRide.setVisibility(View.VISIBLE);
        }
    });


    //End Ride Methods

    tvEndRide = (TextView) findViewById(R.id.tvEndRide);
    tvEndRide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager)
                    getSystemService(LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    Activity#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 Activity#requestPermissions for more details.
                    return;
                }
            }
            Location location = locationManager.getLastKnownLocation(bestProvider);
            end_latitude = location.getLatitude();
            end_longitude = location.getLongitude();

            LatLng latLng = new LatLng(end_latitude, end_longitude);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
            markerOptions.position(latLng);
            mMap.addMarker(markerOptions);
            end_time = System.currentTimeMillis();
            float travel_time = (end_time - start_time) / 60000;

            Location startLocation = new Location("Start Location");
            startLocation.setLatitude(start_latitude);
            startLocation.setLongitude(start_longitude);

            Location endLocation = new Location("End Location");
            endLocation.setLatitude(end_latitude);
            endLocation.setLongitude(end_longitude);


            distance = startLocation.distanceTo(endLocation);
            float fare = (baseRate+((distance/1000)*rate)+(travel_time*2));


            tvEndRide.setVisibility(View.GONE);

            AlertDialog.Builder alertdialogue = new AlertDialog.Builder(MapsActivity.this);
            alertdialogue.setTitle("Fare");
            alertdialogue.setIcon(R.mipmap.ic_launcher);
            alertdialogue.setMessage("Distance travelled is: "+distance + " metres \n Time travelled is: "+travel_time+" minutes \n fare is: "+fare+" INR");
            alertdialogue.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
             public void onClick(DialogInterface dialogInterface, int i) {
             }
            });alertdialogue.show();
            tvStartRide.setVisibility(View.VISIBLE);
        }
    });


    //Rate Methods

    fabRate = (FloatingActionButton) findViewById(R.id.fabRate);
    fabRate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), SetFareRate.class);
            startActivityForResult(i,2);
        }
    });


    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);

    //Get current Location Methods

    fabLocation = (FloatingActionButton) findViewById(R.id.fabLocation);
    fabLocation.setImageResource(R.drawable.ic_gps_fixed_black_24dp);
    fabLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), 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;
            }
            mMap.setMyLocationEnabled(true);
            mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
        }
    });


}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }
    mMap.setMyLocationEnabled(true);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    Location location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(bestProvider, 20000, 0, (LocationListener) this);

}

@Override
public void onLocationChanged(Location location) {
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);


    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mMap.setBuildingsEnabled(true);
    mMap.setIndoorEnabled(true);
    mMap.setBuildingsEnabled(true);
    mMap.setTrafficEnabled(true);
    mMap.getUiSettings().isMyLocationButtonEnabled();
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==2){
       String BaseRate = data.getStringExtra("baseRate");
       String  Rate = data.getStringExtra("rate");

        baseRate = Float.valueOf(BaseRate);
        rate = Float.valueOf(Rate);

    }
}

}

我的第二项活动是这样的:

public class SetFareRate extends AppCompatActivity {

EditText etBaseRate,etRate;
TextView tvSubmit;



@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setfare);

    etBaseRate= (EditText) findViewById(R.id.etBaseRate);
    etRate= (EditText) findViewById(R.id.etRate);
    tvSubmit= (TextView) findViewById(R.id.tvSubmit);


    tvSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String baseRate = etBaseRate.getText().toString();
            String rate = etRate.getText().toString();

            Intent i = new Intent();
            i.putExtra("baseRate",baseRate);
            i.putExtra("rate",rate);
            setResult(2,i);
            Toast.makeText(getApplicationContext(),"Rate Submitted sucessfully",Toast.LENGTH_SHORT).show();
        }
    });

}

}

我在数字格式例外:

        baseRate = Float.valueOf(BaseRate);
        rate = Float.valueOf(Rate);
第一个Activity中的onActvityResult中的

Logcat是:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=2, data=Intent { (has extras) }} to activity {me.nikantchaudhary.taxifare/me.nikantchaudhary.taxifare.MapsActivity}: java.lang.NumberFormatException: Invalid float: ""
at android.app.ActivityThread.deliverResults(ActivityThread.java:3544)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3587)
at android.app.ActivityThread.access$1300(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1334)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5237)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Caused by: java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:308)
at java.lang.Float.parseFloat(Float.java:306)
at java.lang.Float.valueOf(Float.java:343)
at me.nikantchaudhary.taxifare.MapsActivity.onActivityResult(MapsActivity.java:291)
at android.app.Activity.dispatchActivityResult(Activity.java:6184)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3540)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3587) 
at android.app.ActivityThread.access$1300(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1334) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5237) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707) 

请帮助。我不知道如何删除它。

2 个答案:

答案 0 :(得分:0)

if(BaseRate != null&& !BaseRate.isEmpty())
    baseRate = Float.valueOf(BaseRate);

if(Rate != null&& !Rate.isEmpty())
    rate = Float.valueOf(Rate);

答案 1 :(得分:0)

你把一个浮子放入束中,而不是一个字符串。把它作为一个漂浮物取出来。

data.getFloat("baseRate")