我想获取当前的国家/地区名称,城市名称和地址行,但它返回“NULL”。当我发送经度和纬度请求时,它会返回正确的经度和纬度。
country name = null,city name = null,address line = null
public class MainActivity extends Activity {
TextView latitude, longitude, country, city, postalCodeTV, addressLineTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// check if GPS enabled
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
latitude = (TextView)findViewById(R.id.fieldLatitude);
latitude.setText("Latitude: "+stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
longitude = (TextView)findViewById(R.id.fieldLongitude);
longitude.setText("Longitude: "+stringLongitude);
String countryVal = gpsTracker.getCountryName(this);
country = (TextView)findViewById(R.id.fieldCountry);
country.setText("country: "+countryVal);
System.out.println("pakistan "+countryVal);
String cityVal = gpsTracker.getLocality(this);
city = (TextView)findViewById(R.id.fieldCity);
city.setText("city: "+cityVal);
String postalCode = gpsTracker.getPostalCode(this);
postalCodeTV = (TextView)findViewById(R.id.fieldPostalCode);
postalCodeTV.setText("postalCode: "+postalCode);
String addressLine = gpsTracker.getAddressLine(this);
addressLineTV = (TextView)findViewById(R.id.fieldAddressLine);
addressLineTV.setText("addressLine: "+addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.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.menu_main, menu);
return true;
}
}
答案 0 :(得分:1)
您的设备应该可以连接到互联网。如果您没有互联网连接,这些值将为null。您可以使用此功能控制是否有互联网:
public boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null){
return false;
}
else{
return true;
}
}
还要将这些权限添加到清单文件中:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
祝你好运。
答案 1 :(得分:0)
您需要将这些权限添加到清单
中<uses-permission
android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
并在设备/模拟器上打开Gps