我获取数据但无法在TextView中显示数据

问题描述

我正在制作一个帮助应用程序,它显示一些天气数据。我想在textview中显示我的数据,我在logcat中看到此获取的数据。当我想在textview中显示此数据时,它什么也没有显示。supoose我想要在humText中显示湿度,但是什么也没显示

#mainactivity

   private void getCurrentLocation() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    assert locationManager != null;
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                location = task.getResult();
                if (location != null) {
                    //set
                    lat = String.valueOf(location.getLatitude());
                    lon = String.valueOf(location.getLongitude());

                    Geocoder geocoder;
                    List<Address> addresses;
                    geocoder = new Geocoder(MainActivity.this,Locale.getDefault());

                    try {
                        addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
                        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only,check with max available address lines by getMaxAddressLineIndex()
                        String city = addresses.get(0).getLocality();
                        String state = addresses.get(0).getAdminArea();
                        String country = addresses.get(0).getCountryName();
                        String postalCode = addresses.get(0).getPostalCode();
                        String kNownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

                        locationTextView.setText(address);
                    } catch (IOException e) {
                        e.printstacktrace();
                    }

                    //get weather data using latitude and longitude
                    weatherService = apiclient.getRetrofit().create(WeatherService.class);
                    Call<WeatherDataModel> call = weatherService.getCurrentWeatherData(lat,lon,AppId);
                    call.enqueue(new Callback<WeatherDataModel>() {
                        @Override
                        public void onResponse(Call<WeatherDataModel> call,Response<WeatherDataModel> response) {
                            WeatherDataModel weatherDataModel = response.body();
                            assert weatherDataModel != null;
                            //tempText.setText(weatherDataModel.getWeathers().get(0).getDescription());
                            humText.setText((int) weatherDataModel.getMain().getHumidity());
                            //Toast.makeText(getApplicationContext(),weatherDataModel.getWeathers().get(0).getDescription(),Toast.LENGTH_LONG).show();
                        }
                        @Override
                        public void onFailure(Call<WeatherDataModel> call,Throwable t) {

                        }
                    });

                } else {
                    LocationRequest locationRequest = new LocationRequest()
                            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                            .setInterval(10000)
                            .setFastestInterval(1000)
                            .setNumUpdates(1);

                    LocationCallback locationCallback = new LocationCallback() {
                        @Override
                        public void onLocationResult(LocationResult locationResult) {
                            super.onLocationResult(locationResult);
                            Location location1 = locationResult.getLastLocation();
                            //set
//                                locationTextView.setText(location1.getLatitude() + "," + String.valueOf(location1.getLongitude()));
                        }
                    };
                    fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,Looper.myLooper());
                }

            }
        });
    } else {
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }
}

#weatherdatamodel

@Serializedname("coord")
public Coord coord;
@Serializedname("weather")
public List<Weather> weathers = new ArrayList<>();
@Serializedname("main")
public Main main;
@Serializedname("wind")
public Wind wind;


public WeatherDataModel(Coord coord,List<Weather> weathers,Main main,Wind wind) {
    this.coord = coord;
    this.weathers = weathers;
    this.main = main;
    this.wind = wind;
}


public Coord getCoord() {
    return coord;
}

public void setCoord(Coord coord) {
    this.coord = coord;
}

public List<Weather> getWeathers() {
    return weathers;
}

public void setWeathers(List<Weather> weathers) {
    this.weathers = weathers;
}

public Main getMain() {
    return main;
}

public void setMain(Main main) {
    this.main = main;
}

public Wind getwind() {
    return wind;
}

public void setwind(Wind wind) {
    this.wind = wind;
}

#weatherService

   public interface WeatherService {
 @GET("data/2.5/weather?")
 Call<WeatherDataModel> getCurrentWeatherData(@Query("lat") String lat,@Query("lon") String lon,@Query("APPID") String app_id);
 }

#apiclient

   public static Retrofit getRetrofit(){

    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MainActivity.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    return retrofit;
}


public static WeatherService getCurrentWeatherData(){
    WeatherService userData = getRetrofit().create(WeatherService.class);
    return userData;
}

Logcat:

Logcat result

我该如何解决。谢谢。

解决方法

所有网络调用均在额外的线程上执行,但您只能在主线程(也称为UI线程)中触摸UI。因此,onResponse应该切换到UI线程以更改TextView。

同样,当您尝试将int传递给setText的{​​{1}}时,系统会尝试获取具有指定ID的String resouce,因此,如果要精确打印获取的数据,有必要将其转换为String。

因此,TextView将是:

onResponse