我想通过点击按钮在tvLatitude
和tvLongitude
(TextView
' s)中显示纬度和经度。它不适用于我目前拥有的代码,您可以看到以下代码。问题是当控件到达字符串latitude = Double.toString(loc.getLatitude());
时,程序停止运行。
有谁可以告诉我为什么loc.getLatitude
和loc.getLongitude
没有回复?
package mk.bukhari.loctrack;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements LocationListener {
TextView tvLat, tvLon;
Button btnLoc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
tvLat = (TextView) findViewById(R.id.tvLatitude);
tvLon = (TextView) findViewById(R.id.tvLongitude);
btnLoc = (Button) findViewById(R.id.btnLocation);
final LocationManager locman = (LocationManager)
getSystemService(LOCATION_SERVICE);
locman.requestLocationUpdates("gps", 0, 0, this);
btnLoc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("LocTrack", "Button Clicked");
Location loc = locman.getLastKnownLocation("gps");
onLocationChanged(loc);
}
});
}
}
}
@Override
public void onLocationChanged(Location loc) {
Log.d("LocTrack", "Entering onLacationChanged");
String latitude = Double.toString(loc.getLatitude());
String longitude = Double.toString(loc.getLongitude());
Log.d("LocTrack", "Setting txt in tv");
tvLat.setText(latitude);
tvLon.setText(longitude);
}
@Override
public void onProviderDisabled(String arg0) {}
@Override
public void onProviderEnabled(String arg0) {}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
答案 0 :(得分:0)
好的,似乎您的位置返回null,请尝试以这种方式更改代码:
@Override
public void onLocationChanged(Location loc) {
Log.d("LocTrack", "Entering onLacationChanged");
if(loc != null) { //Add this validation
String latitude = Double.toString(loc.getLatitude());
String longitude = Double.toString(loc.getLongitude());
Log.d("LocTrack", "Setting txt in tv");
tvLat.setText(latitude);
tvLon.setText(longitude);
} else //If loc is null then inform the user
Toast.makeText(this, "Unable to find your location, try again", Toast.LENGTH_SHORT).show();
}
答案 1 :(得分:0)
好像你使用了错误的提供商。
尝试拨打
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, this);
然后在onClick(View v)
Location loc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER);