我有一个方法getLastLocation()包含两个字符串city和country,问题是何时
我尝试将字符串设置为在我获得空值的方法之外的textview,仅当我将字符串设置为该方法内部的textview时,它才起作用。
任何帮助将不胜感激。
这是我的代码:
getLastLocation();
String city;
String country;
Textview cityText = (TextView) findViewById(R.id.tv_city);
Textview countryText = (TextView) findViewById(R.id.tv_country);
cityText .setText(country);
countryText .setText(city);
@SuppressLint("MissingPermission")
public void getLastLocation(){
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
MyLat = location.getLatitude();
MyLong = location.getLongitude();
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
@SuppressWarnings("ResourceType") Location location1 = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location1.getLatitude(), location1.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
city = addresses.get(0).getCountryName(); ///////string I want to get <<<---------
country = addresses.get(0).getLocality(); ///////string I want to get <<<---------
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
);
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
答案 0 :(得分:0)
根据我从您的问题中得到的信息, 在调用getLastLocation()函数之前,您正在将字符串值设置为textview,而此时您的字符串(城市和国家)为空或为null;
首先,您必须调用该方法,然后将其设置为texview,这样就可以正常工作。
getLastLocation() ;
cityText .setText(country);
countryText .setText(city);
答案 1 :(得分:0)
mFusedLocationClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {}
您的代码中有一个侦听器。即使您首先将getLastLocation()放在首位,也无法保证将为城市,国家/地区字符串分配值。
public void onComplete(@NonNull Task<Location> task)
上述方法仅在相应任务完成时执行。
无论您在getLastLocation()下面编写的任何代码都将执行,而不必触发onCompleted()。
因此,您在textViews中得到的是空值而不是实际值。
为避免这种情况,您必须在OnComplete()方法内更新textviews。
如果您仍要更新getLastLocation()之外的textview,请添加延迟以设置textView的值
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
cityText .setText(country);
countryText .setText(city);
}
},5000); //textviews will be set value after 5 seconds, assuming that OnComplete() inside getLastLocation() will be triggered within 5 seconds.