【问题标题】:I fetch data but can't show data in textview我获取数据但无法在 textview 中显示数据
【发布时间】:2021-01-16 11:56:26
【问题描述】:

我正在制作一个帮助应用程序,它显示一些天气数据。我想在 textview 中显示我的数据,我在 logcat 中看到了这个获取数据。当我想在 textview 中显示这个数据时它什么都不显示。假设我想在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:

我该如何解决这个问题。谢谢。

【问题讨论】:

    标签: java android retrofit2 fetch-api data-retrieval


    【解决方案1】:

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

    同样,当您尝试将int 传递给setTextTextView 时,系统会尝试获取具有指定id 的String 资源,因此如果您想准确打印获取的数据,则需要对其进行转换到字符串。

    所以,onResponse 将是:

    public void onResponse(Call<WeatherDataModel> call, Response<WeatherDataModel> response) {
      WeatherDataModel weatherDataModel = response.body();
      assert weatherDataModel != null;
      runOnUiThread(new Runnable {
        @Override
        public void run() {
           humText.setText(String.valueOf(weatherDataModel.getMain().getHumidity()));
        }
      });
    }
    

    【讨论】:

    • logcat中是否有异常说明?
    • 无异常说明?
    • @user10997009,weatherDataModel 是否包含实际的main 属性及其在onResponse 中的数据?
    • 您使用什么天气服务 API?分享链接,我会尝试重现问题
    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    相关资源
    最近更新 更多