1

我正在使用该位置,但现在每当我单击应用程序上的按钮时,我都会不断收到 nullPointerException。该按钮刷新显示的位置。位置以纬度、经度、街道地址、城市、国家和邮政地址显示。这是下面的代码。

package com.example.metrorails;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    CurrentPosition currentPosition;
    String address;
    String city;
    String country;
    String postalCode;


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

        Button refresh;
        refresh = (Button)findViewById(R.id.refresh);
        refresh.setOnClickListener(new OnClickListener() {

                @Override
            public void onClick(View v) {
                currentPosition = new    CurrentPosition(MainActivity.this);
                TextView showresults = (TextView) findViewById(R.id.show_results);
                showresults.setTextSize(20);

                if(currentPosition.canGetLocation()){

                    double latitude = currentPosition.getLatitude();
                    double longitude = currentPosition.getLongitude();
                    showresults.setText("current latitude: "+latitude +"\n current longitude: "+longitude+ 
                        "\n Address is: " +currentPosition.getAddress() + "\n city is: "+currentPosition.getCity()+
                        "\n Current Country is: "+currentPosition.getCountry() +"\n Area Code : "+currentPosition.getPostalCode());



                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    currentPosition.showSettingsAlert();    
                }               
            }
        });
    }

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

}

我仍然有这个程序的问题。这是下面的logcat。

09-09 18:56:52.393: E/AndroidRuntime(1882): FATAL EXCEPTION: main
09-09 18:56:52.393: E/AndroidRuntime(1882): java.lang.NullPointerException
09-09 18:56:52.393: E/AndroidRuntime(1882):     at   android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.location.GeocoderParams.  <init>(GeocoderParams.java:50)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.location.Geocoder.<init>(Geocoder.java:83)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at com.example.metrorails.CurrentPosition.<init>(CurrentPosition.java:71)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at com.example.metrorails.MainActivity$1.onClick(MainActivity.java:31)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.view.View.performClick(View.java:4240)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.view.View$PerformClick.run(View.java:17721)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.os.Handler.handleCallback(Handler.java:730)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.os.Looper.loop(Looper.java:137)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at android.app.ActivityThread.main(ActivityThread.java:5103)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at java.lang.reflect.Method.invokeNative(Native Method)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at java.lang.reflect.Method.invoke(Method.java:525)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-09 18:56:52.393: E/AndroidRuntime(1882):     at dalvik.system.NativeStart.main(Native Method)
09-09 18:57:01.512: I/Process(1882): Sending signal. PID: 1882 SIG: 9

下面是 CurrentPosition 类。

package com.example.metrorails;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public  class CurrentPosition extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
public static String address;
public static String city;
private static String country;
private static String postalCode;


// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public String getAddress(){

    return address;
}
public String getCity(){

        return city;
}
public String getCountry(){

    return country;
}
public String getPostalCode(){

    return postalCode;
}





public CurrentPosition(Context context) {
    this.mContext = context;
    getLocation();
}

public void getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            Geocoder geocode = new Geocoder(this, Locale.getDefault());
                                List<Address> addresses;
                            try {
                                    addresses = geocode.getFromLocation(latitude,longitude, 1);
                                this.address = addresses.get(0).getAddressLine(0);
                                this.city = addresses.get(0).getAddressLine(1);
                                this.country = addresses.get(0).getAddressLine(2);
                                this.postalCode =  addresses.get(0).getPostalCode();
                                } catch (IOException e) {

                                    e.printStackTrace();
                            }
                        }
                    }
                }
            }

    }} catch (Exception e) {
        e.printStackTrace();
    }   

   this.location = location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(CurrentPosition.this);
    }       
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
 }
4

0 回答 0