我在按下按钮时(在搜索按钮上)获取NullpointerException java.lang.NullPointerException

时间:2014-02-07 13:50:28

标签: android

在我点击“btnSearch”按钮后在etSearch(EDitText)中写了一个地址后,它应该在地图中显示地址。但它给了我错误。可以帮助我

错误

02-07 19:34:30.251: E/AndroidRuntime(24364): FATAL EXCEPTION: main
02-07 19:34:30.251: E/AndroidRuntime(24364): java.lang.NullPointerException
02-07 19:34:30.251: E/AndroidRuntime(24364):    at com.mamun.tasktest.MapActivity$GeocoderTask.onPostExecute(MapActivity.java:178)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at com.mamun.tasktest.MapActivity$GeocoderTask.onPostExecute(MapActivity.java:1)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at android.os.AsyncTask.finish(AsyncTask.java:631)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at android.os.Looper.loop(Looper.java:137)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at android.app.ActivityThread.main(ActivityThread.java:4960)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at java.lang.reflect.Method.invokeNative(Native Method)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at java.lang.reflect.Method.invoke(Method.java:511)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-07 19:34:30.251: E/AndroidRuntime(24364):    at dalvik.system.NativeStart.main(Native Method)


public class MapActivity extends Activity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {

    private LocationManager manager;

    private TextView tvAddress;
    private Button btnSearch;
    private EditText etSearch;
    private LocationClient locationClient;
    private GoogleMap googleMap;
    private MapFragment mapFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.map);

        manager = (LocationManager) getSystemService(LOCATION_SERVICE);

        tvAddress = (TextView) findViewById(R.id.tvaddress);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        etSearch= (EditText)findViewById(R.id.etSearch);
        mapFragment = (MapFragment) getFragmentManager().findFragmentById(
                R.id.maps);
        googleMap = mapFragment.getMap();
        locationClient = new LocationClient(this, this, this);

    }

    public void onSearch(View v) {

           // Getting user input location
           String location = etSearch.getText().toString();

           if(location!=null && !location.equals("")){
               new GeocoderTask().execute(location);
           }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        locationClient.connect();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        locationClient.disconnect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Location currentLocation = locationClient.getLastLocation();
        double lat = currentLocation.getLatitude();
        double lng = currentLocation.getLongitude();
        // txtLocation.setText(lat + ", " + lng);

        Geocoder geocoder = new Geocoder(this);
        try {
            ArrayList<Address> address = (ArrayList<Address>) geocoder
                    .getFromLocation(currentLocation.getLatitude(),
                            currentLocation.getLongitude(), 5);
            Address addr = address.get(0);
            String currentAddress = (addr.getAddressLine(0) + "-"
                    + addr.getAdminArea() + "-" + addr.getLocality() + "-"
                    + addr.getPostalCode() + "-" + addr.getCountryCode());
            MarkerOptions options = new MarkerOptions();
            options.position(new LatLng(lat, lng));
            options.title(currentAddress);
            options.snippet("Current location");
            options.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
            if (googleMap != null) {
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(lat, lng), 14.0f));
                googleMap.addMarker(options);
            } else {
                Toast.makeText(getApplicationContext(), "Map is null",
                        Toast.LENGTH_LONG).show();
            }

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

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }

    // An AsyncTask class for accessing the GeoCoding Web Service
    private class GeocoderTask extends AsyncTask<String, Void, ArrayList<Address>>{

        @Override
        protected ArrayList<Address> doInBackground(String... locationName) {
            // Creating an instance of Geocoder class
            Geocoder geocoder = new Geocoder(getBaseContext());
            ArrayList<Address> addresses = null;

            try {
                // Getting a maximum of 3 Address that matches the input text
                addresses = (ArrayList<Address>) geocoder.getFromLocationName(locationName[0], 3);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addresses;
        }

        @Override
        protected void onPostExecute(ArrayList<Address> addresses) {

            if(addresses==null || addresses.size()==0){
                Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
            }

            // Clears all the existing markers on the map
           // googleMap.clear();

            // Adding Markers on Google Map for each matching address
            for(int i=0;i<addresses.size();i++){

                Address address = (Address) addresses.get(i);

                // Creating an instance of GeoPoint, to display in Google Map
                LatLng latLng ;  
        latLng = new LatLng(address.getLatitude(), address.getLongitude());

                String addressText = String.format("%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());
                MarkerOptions markerOptions = new MarkerOptions();
               // markerOptions = new MarkerOptions();
                markerOptions.position( latLng);
                markerOptions.title(addressText);

                googleMap.addMarker(markerOptions);

                // Locate the first location
                if(i==0)
                    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

当地址为空时,您必须退出该函数。

@Override
protected void onPostExecute(ArrayList<Address> addresses) {
   if(addresses==null || addresses.size()==0){
       Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
       return;
   }