我跟着這個link來做一個GPS跟蹤應用程序。當我按下按鈕獲取位置時,應用程序已停止。我檢查了LogCat,並在displayCurrentLocation()中顯示錯誤。當我從模擬器運行應用程序時,可以跟蹤位置嗎?我可以看到在DDMS中進行位置控制的手動設置。跟蹤模擬器的位置是否有用?Android:我如何跟蹤模擬器的位置?
這是我的活動代碼。
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
LocationClient mLocationClient;
private TextView addressLabel;
private TextView locationLabel;
private Button getLocationBtn;
private Button disconnectBtn;
private Button connectBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationLabel = (TextView) findViewById(R.id.locationLabel);
addressLabel = (TextView) findViewById(R.id.addressLabel);
getLocationBtn = (Button) findViewById(R.id.getLocation);
getLocationBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
displayCurrentLocation();
}
});
disconnectBtn = (Button) findViewById(R.id.disconnect);
disconnectBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mLocationClient.disconnect();
locationLabel.setText("Got disconnected....");
}
});
connectBtn = (Button) findViewById(R.id.connect);
connectBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mLocationClient.connect();
locationLabel.setText("Got connected....");
}
});
// Create the LocationRequest object
mLocationClient = new LocationClient(this, this, this);
}
@Override
protected void onStart() {
super.onStart();
// Connect the client.
mLocationClient.connect();
locationLabel.setText("Got connected....");
}
@Override
protected void onStop() {
// Disconnect the client.
mLocationClient.disconnect();
super.onStop();
locationLabel.setText("Got disconnected....");
}
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Display the error code on failure
Toast.makeText(this, "Connection Failure : " +
connectionResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
}
public void displayCurrentLocation() {
// Get the current location's latitude & longitude
Location currentLocation = mLocationClient.getLastLocation();
String msg = "Current Location: " +
Double.toString(currentLocation.getLatitude()) + "," +
Double.toString(currentLocation.getLongitude());
// Display the current location in the UI
locationLabel.setText(msg);
// To display the current address in the UI
(new GetAddressTask(this)).execute(currentLocation);
}
/*
* Following is a subclass of AsyncTask which has been used to get
* address corresponding to the given latitude & longitude.
*/
private class GetAddressTask extends AsyncTask<Location, Void, String>{
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
/*
* When the task finishes, onPostExecute() displays the address.
*/
@Override
protected void onPostExecute(String address) {
// Display the current address in the UI
addressLabel.setText(address);
}
@Override
protected String doInBackground(Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available),
* city, and country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ?
address.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found";
}
}
}
XML代碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/getLocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/get_location"/>
<Button android:id="@+id/disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/disconnect"/>
<Button android:id="@+id/connect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/connect"/>
<TextView
android:id="@+id/locationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/addressLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
請指引我解決這個問題。提前致謝。
07-26 05:02:38.399: D/AndroidRuntime(3408): Shutting down VM
07-26 05:02:38.399: W/dalvikvm(3408): threadid=1: thread exiting with uncaught exception (group=0xb2d1eb20)
07-26 05:02:38.399: E/AndroidRuntime(3408): FATAL EXCEPTION: main
07-26 05:02:38.399: E/AndroidRuntime(3408): Process: com.example.gpstracker, PID: 3408
07-26 05:02:38.399: E/AndroidRuntime(3408): java.lang.NullPointerException
07-26 05:02:38.399: E/AndroidRuntime(3408): at com.example.gpstracker.MainActivity.displayCurrentLocation(MainActivity.java:103)
07-26 05:02:38.399: E/AndroidRuntime(3408): at com.example.gpstracker.MainActivity$1.onClick(MainActivity.java:47)
07-26 05:02:38.399: E/AndroidRuntime(3408): at android.view.View.performClick(View.java:4438)
07-26 05:02:38.399: E/AndroidRuntime(3408): at android.view.View$PerformClick.run(View.java:18422)
07-26 05:02:38.399: E/AndroidRuntime(3408): at android.os.Handler.handleCallback(Handler.java:733)
07-26 05:02:38.399: E/AndroidRuntime(3408): at android.os.Handler.dispatchMessage(Handler.java:95)
07-26 05:02:38.399: E/AndroidRuntime(3408): at android.os.Looper.loop(Looper.java:136)
07-26 05:02:38.399: E/AndroidRuntime(3408): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-26 05:02:38.399: E/AndroidRuntime(3408): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 05:02:38.399: E/AndroidRuntime(3408): at java.lang.reflect.Method.invoke(Method.java:515)
07-26 05:02:38.399: E/AndroidRuntime(3408): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-26 05:02:38.399: E/AndroidRuntime(3408): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-26 05:02:38.399: E/AndroidRuntime(3408): at dalvik.system.NativeStart.main(Native Method)
不要只是告訴我們有一個崩潰,發佈堆棧跟蹤,以便我們可以看到它是什麼。最有可能的是lastLocation返回null,因爲它沒有最後一個位置。 –
是的,我編輯了堆棧跟蹤。 – Sridhar
它是我的想法 - 它沒有準備好位置,並且您調用getLastLocation,因此它返回null。你不能認爲它總是知道一個位置。如果你絕對需要一個位置,請求位置更新。 GetLastLocation不應該依賴於 –