2016-10-17 74 views
0

我的第一個活動是這樣的:如何刪除NumberFormat異常?

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); 

in onActvityResult in first Activity。

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)  

請Help.I我沒有得到任何線索,如何刪除此。

+0

很明顯,該字符串值爲空。但是if語句或try catch。或者,輸入一個值 –

+0

無效浮點數:看起來可能是類型不匹配? – hellyale

+0

http://stackoverflow.com/a/39850130/4723795 – xenteros

回答

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

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

從錯誤消息中,您可以推斷傳入的字符串不爲空,但實際上是一個空字符串。 –

+0

該字符串是空的,而不是空的 –

+0

現在檢查我的答案 – sasikumar

0

你把一個float放到bundle中,而不是一個字符串。以浮點形式返回。

data.getFloat("baseRate")