我正在测试我的活动以获得GPS坐标(lat,long),但是当点击Register按钮时,log cat显示错误。 我打算测试这段代码
Log.d(ACCESSIBILITY_SERVICE, Double.toString(gps.getLatitude()));
这是我的代码。 的 MainActivity.java
public class MainActivity extends Activity {
protected static final String PREFS_NAME = null;
String prefName = "MyPref";
EditText editText01, editText02;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText01 = (EditText) findViewById(R.id.EditText01); //Trusted phone number
editText02 = (EditText) findViewById(R.id.EditText02); //Email address
Button RegisterButton = (Button) findViewById(R.id.btnRegister); //RegisterButton
RegisterButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("trustedNum", editText01.getText().toString());
editor.putString("Email", editText02.getText().toString());
TelephonyManager tm = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
editor.putString("storedSimSerial", tm.getSimSerialNumber());
editor.commit();
Log.d(ACCESSIBILITY_SERVICE, Double.toString(gps.getLatitude()));
Toast.makeText(getApplicationContext(), "saved", 3000).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
GPSTracker.java package com.example.sms;
public class GPSTracker 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
// 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 GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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;
// 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 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();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.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;
}
}
的Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".BootComplete">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.READ_PHONE_STATE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:name="com.example.sms.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ErrorCode显示
03-12 18:10:56.200: E/AndroidRuntime(2368): FATAL EXCEPTION: main
03-12 18:10:56.200: E/AndroidRuntime(2368): java.lang.NullPointerException
03-12 18:10:56.200: E/AndroidRuntime(2368): at com.example.sms.MainActivity$1.onClick(MainActivity.java:56)
03-12 18:10:56.200: E/AndroidRuntime(2368): at android.view.View.performClick(View.java:4211)
03-12 18:10:56.200: E/AndroidRuntime(2368): at android.view.View$PerformClick.run(View.java:17267)
03-12 18:10:56.200: E/AndroidRuntime(2368): at android.os.Handler.handleCallback(Handler.java:615)
03-12 18:10:56.200: E/AndroidRuntime(2368): at android.os.Handler.dispatchMessage(Handler.java:92)
03-12 18:10:56.200: E/AndroidRuntime(2368): at android.os.Looper.loop(Looper.java:137)
03-12 18:10:56.200: E/AndroidRuntime(2368): at android.app.ActivityThread.main(ActivityThread.java:4898)
03-12 18:10:56.200: E/AndroidRuntime(2368): at java.lang.reflect.Method.invokeNative(Native Method)
03-12 18:10:56.200: E/AndroidRuntime(2368): at java.lang.reflect.Method.invoke(Method.java:511)
03-12 18:10:56.200: E/AndroidRuntime(2368): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
03-12 18:10:56.200: E/AndroidRuntime(2368): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
03-12 18:10:56.200: E/AndroidRuntime(2368): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
哦圣洁的moly !您设置PREFS_NAME = null
然后在代码中使用它!你忘记了初始化吗?
答案 1 :(得分:0)
这里
Log.d(ACCESSIBILITY_SERVICE, Double.toString(gps.getLatitude()));
^^^
gps
为null,您必须先初始化gps
实例,然后再将其用作:
gps=new GPSTracker(MainActivity.this); //<<< initialize here
Log.d(ACCESSIBILITY_SERVICE, Double.toString(gps.getLatitude()));
答案 2 :(得分:0)
GPSTracker gps在哪里初始化?你正在直接使用它。