android asynctask-空指针映射代码中的异常



以下代码可以做到这一点:

用户在文本框中输入位置或位置,然后单击按钮。单击按钮时,将在用户输入的位置放置一个标记。不幸的是,这引发了一个空指针异常。

请帮我清除它。我已经包含了logcat中显示的错误。

错误在doInBackground((中,地址为null。

import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Address;
import android.location.Geocoder;
import java.util.List;

public class MapsActivity extends FragmentActivity implements      GoogleMap.OnMapLongClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LatLng latLng;
MarkerOptions markerOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    Button btn_find = (Button) findViewById(R.id.btn_find);
    View.OnClickListener findClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Getting reference to EditText to get the user input location
            EditText etLocation = (EditText) findViewById(R.id.et_location);
            // Getting user input location
            String location;
            location = etLocation.getText().toString();

            if( !location.equals("")){
                new GeocoderTask(getApplicationContext()).execute(location);
            }
        }
    };
    // Setting button click event listener for the find button
    btn_find.setOnClickListener(findClickListener);
    setUpMapIfNeeded();
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
    private Context mainContxt;

    public GeocoderTask(Context con){
        mainContxt=con;
    }
    @Override
    protected List<Address> doInBackground(String... locationName) {
        List<Address> geoResults=null;
        Geocoder geocoder = new Geocoder(mainContxt);
        try {
            geoResults = geocoder.getFromLocationName(locationName[0], 1);
            while (geoResults.size()==0) {
                geoResults = geocoder.getFromLocationName(locationName[0], 1);
            }
            if (geoResults.size()>0) {
                Address  addresses = geoResults.get(0);
            }
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
        // Creating an instance of Geocoder class

        return geoResults;
    }

    @Override
    protected void onPostExecute(List<Address> addresses) {
        if(addresses==null ){
            Toast.makeText(MapsActivity.this, "No Location found", Toast.LENGTH_LONG).show();
        }
        // Clears all the existing markers on the map
        mMap.clear();
        if(addresses!=null)
        {  int t=addresses.size();
            // Adding Markers on Google Map for each matching address
            for(int i=0;i<t;i++){
                Address address =  addresses.get(i);
                // Creating an instance of GeoPoint, to display in Google Map
                latLng = new LatLng(address.getLatitude(), address.getLongitude());
                String addressText = String.format("%s, %s",
                        address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                        address.getCountryName());
                markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title(addressText);
                mMap.addMarker(markerOptions);
                // Locate the first location
                if(i==0)
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }}}}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}
/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setOnMapLongClickListener(this);
        if (mMap != null) {
            setUpMap();
        }
    }
}
// An AsyncTask class for accessing the GeoCoding Web Service

private void setUpMap() {

}
@Override
public void onMapLongClick(LatLng latLng) {
    mMap.addMarker(new MarkerOptions().position(latLng).title("Custom location"));
    Toast.makeText(MapsActivity.this,"latlong is"+latLng, Toast.LENGTH_LONG).show();
}
}

**我的日志猫显示这个**

06-03 17:08:55.990  19880-19880/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at  com.example.sweth.reached2.MapsActivity$GeocoderTask.onPostExecute(MapsActivity.java:143)
        at com.example.sweth.reached2.MapsActivity$GeocoderTask.onPostExecute(MapsActivity.java:114)
        at android.os.AsyncTask.finish(AsyncTask.java:602)
        at android.os.AsyncTask.access$600(AsyncTask.java:156)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4441)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

您正在执行错误的if check

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

试着在上面这样做

 if(addresses==null){
    Toast.makeText(MapsActivity.this, "No Location found", Toast.LENGTH_LONG).show();
}

Null对象不应具有任何大小。您正在获取null地址,并检查null对象的大小。从而得到nullpointer exception

更新你也可以这样做

if(addresses==null){
        Toast.makeText(MapsActivity.this, "No Location found", Toast.LENGTH_LONG).show();
    }else{
if(addresses.size() == 0){
        Toast.makeText(MapsActivity.this, "Zero Location found", Toast.LENGTH_LONG).show();
    }else if(addresses.size() == 1){
         Toast.makeText(MapsActivity.this, "one Location found", Toast.LENGTH_LONG).show();
    }
}

相关内容

  • 没有找到相关文章

最新更新