我在我的GPSTracker类中调用get latitude的行上得到一个空指针异常。有什么想法吗?我也在使用移动设备,而不是DDMS。我已经完成了System.out.println(gps.getLatitude())
并确实返回null,但我无法弄清楚原因。手机上的GPS也已打开
这是我的班级
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
Double latitude;
Double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; //1 minute
protected LocationManager locationManager;
public GPSTracker (Context context){
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
System.out.println(location.getLatitude());
if(!isGPSEnabled && !isNetworkEnabled){
//no network provider is enabled
} else{
this.canGetLocation = true;
// First get location from Network provider
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 (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();
}
}
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return location;
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
System.out.println(latitude);
return 0.0;
}
System.out.println(latitude);
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
System.out.println(longitude);
return 0.0;
}
return longitude;
}
/**
* Function to show setting alert dialog
*/
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 and enable GPS?");
//Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
//On Pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
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();
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
@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;
}
}
我解析我的JSON
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String myurl) {
// Making HTTP request
try {
// defaultHttpClient
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("HttpConnection", "The response is: " + response);
is = conn.getInputStream();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我的主要活动
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView weather = null;
public TextView summary = null;
public TextView icon = null;
public JSONObject currentTemperature = null;
public String temperature = "";
public String weatherSummary = "";
public String weatherIcon = "";
public GPSTracker gps;
public double latitude = 0;
public double longitude = 0;
public String myUrl;
public TextView latitudeView = null;
public TextView longitudeView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView) findViewById(R.id.weather);
summary = (TextView) findViewById(R.id.weather_summary);
icon = (TextView) findViewById(R.id.string_icon);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
gps = new GPSTracker(MainActivity.this);
myUrl = "https://api.forecast.io/forecast/5530508d3568e57848d53bf10cfade1f/35.9033,-79.0440";
//gps.getLatitude() + "," + gps.getLongitude();
double lat = gps.getLatitude();
double longitude = gps.getLatitude();
latitudeView.setText(String.valueOf(lat));
longitudeView.setText(String.valueOf(longitude));
}
/* public String convertLatitude(){
latitude = gps.getLatitude();
String latitude2 = Double.toString(latitude);
return latitude2;
}*/
/* public String convertLongitude(){
longitude = gps.getLongitude();
String longitude2 = Double.toString(longitude);
return longitude2;
}*/
//do in background method to call JSON Parser
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
@Override
protected String doInBackground(String... arg0){
try {
// instantiate our json parser
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(myUrl);
JSONObject current = json.getJSONObject("currently");
temperature = current.getString("temperature");
weatherSummary = current.getString("summary");
weatherIcon = current.getString("icon");
} catch (JSONException e) {
e.printStackTrace();
}
return myUrl;
}
@Override
protected void onPostExecute(String strFromDoInBg) {
weather.setText(temperature);
summary.setText(weatherSummary);
icon.setText(weatherIcon);
}
}
}
我的LogCat
07-12 15:13:31.373: W/System.err(32167): java.lang.NullPointerException
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.GPSTracker.getLocation(GPSTracker.java:42)
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.GPSTracker.<init>(GPSTracker.java:33)
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.MainActivity.onCreate(MainActivity.java:39)
07-12 15:13:31.378: W/System.err(32167): at android.app.Activity.performCreate(Activity.java:5451)
07-12 15:13:31.378: W/System.err(32167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.access$900(ActivityThread.java:175)
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
07-12 15:13:31.378: W/System.err(32167): at android.os.Handler.dispatchMessage(Handler.java:102)
07-12 15:13:31.378: W/System.err(32167): at android.os.Looper.loop(Looper.java:146)
07-12 15:13:31.378: W/System.err(32167): at android.app.ActivityThread.main(ActivityThread.java:5602)
07-12 15:13:31.378: W/System.err(32167): at java.lang.reflect.Method.invokeNative(Native Method)
07-12 15:13:31.378: W/System.err(32167): at java.lang.reflect.Method.invoke(Method.java:515)
07-12 15:13:31.378: W/System.err(32167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
07-12 15:13:31.378: W/System.err(32167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
07-12 15:13:31.378: W/System.err(32167): at dalvik.system.NativeStart.main(Native Method)
07-12 15:13:31.378: I/System.out(32167): null
07-12 15:13:31.378: D/AndroidRuntime(32167): Shutting down VM
07-12 15:13:31.378: W/dalvikvm(32167): threadid=1: thread exiting with uncaught exception (group=0x41886c08)
07-12 15:13:31.378: W/System.err(32167): java.net.MalformedURLException
07-12 15:13:31.378: W/System.err(32167): at java.net.URL.<init>(URL.java:152)
07-12 15:13:31.378: W/System.err(32167): at java.net.URL.<init>(URL.java:125)
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.JSONParser.getJSONFromUrl(JSONParser.java:29)
07-12 15:13:31.378: W/System.err(32167): at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:76)
07-12 15:13:31.378: E/AndroidRuntime(32167): FATAL EXCEPTION: main
07-12 15:13:31.378: E/AndroidRuntime(32167): Process: rafa.weatherapp, PID: 32167
07-12 15:13:31.378: E/AndroidRuntime(32167): java.lang.RuntimeException: Unable to start activity ComponentInfo{rafa.weatherapp/rafa.weatherapp.MainActivity}: java.lang.NullPointerException
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.access$900(ActivityThread.java:175)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.os.Handler.dispatchMessage(Handler.java:102)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.os.Looper.loop(Looper.java:146)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.main(ActivityThread.java:5602)
07-12 15:13:31.378: E/AndroidRuntime(32167): at java.lang.reflect.Method.invokeNative(Native Method)
07-12 15:13:31.378: E/AndroidRuntime(32167): at java.lang.reflect.Method.invoke(Method.java:515)
07-12 15:13:31.378: E/AndroidRuntime(32167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
07-12 15:13:31.378: E/AndroidRuntime(32167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
07-12 15:13:31.378: E/AndroidRuntime(32167): at dalvik.system.NativeStart.main(Native Method)
07-12 15:13:31.378: E/AndroidRuntime(32167): Caused by: java.lang.NullPointerException
07-12 15:13:31.378: E/AndroidRuntime(32167): at rafa.weatherapp.GPSTracker.getLatitude(GPSTracker.java:92)
07-12 15:13:31.378: E/AndroidRuntime(32167): at rafa.weatherapp.MainActivity.onCreate(MainActivity.java:43)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.Activity.performCreate(Activity.java:5451)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
07-12 15:13:31.378: E/AndroidRuntime(32167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
07-12 15:13:31.378: E/AndroidRuntime(32167): ... 11 more
07-12 15:13:31.383: W/ActivityManager(2431): Force finishing activity rafa.weatherapp/.MainActivity
07-12 15:13:31.388: W/System.err(32167): at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:1)
07-12 15:13:31.388: W/System.err(32167): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-12 15:13:31.388: W/System.err(32167): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-12 15:13:31.388: W/System.err(32167): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-12 15:13:31.388: W/System.err(32167): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-12 15:13:31.388: W/System.err(32167): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-12 15:13:31.388: W/System.err(32167): at java.lang.Thread.run(Thread.java:841)
07-12 15:13:31.388: E/Buffer Error(32167): Error converting result java.lang.NullPointerException: lock == null
07-12 15:13:31.393: E/JSON Parser(32167): Error parsing data org.json.JSONException: End of input at character 0 of
答案 0 :(得分:0)
检查权限的位置是否在清单中的适当位置。如果您发布清单的内容,它可能会有所帮助。
答案 1 :(得分:0)
替换所有
System.out.println("")
带
Log.d("", "");
答案 2 :(得分:0)
尝试更换:
gps = new GPSTracker(MainActivity.this);
带
gps = new GPSTracker(getApplicationContext());
也
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();
}
}
如果您之前从未真正获得过某个位置,则getLastKnownLocation上的可能为null。我建议将latitude = location.getLatitude()调用放入onLocationChanged方法,这样可以保证您异步获取正确的位置。