片段中的 Asynctask 未到达 onPostExecute

Posted

技术标签:

【中文标题】片段中的 Asynctask 未到达 onPostExecute【英文标题】:Asynctask in fragment is not getting to onPostExecute 【发布时间】:2019-01-25 19:21:21 【问题描述】:

我正在使用 openweathermap api(5 天预报),并且正在使用 GSON 解析数据。 asynctask 与服务器连接,但它不去 onPostExecute。它在收到响应 200 代码后终止。我认为它设置正确,但没有完成程序:

   private static class GetWeatherAync extends AsyncTask<Context, Void, List<ForecastWeatherList>> 
    private String TAG = GetWeatherAync.class.getSimpleName();
    private final String serviceUrl;
    private Context mContext;
    private Listener listener;
    HttpURLConnection urlConnection = null;


    public GetWeatherAync(Listener listener, Object mStatusView, Object api_key) 
        this.listener = listener;
        this.serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + "Baltimore" + api_key;
    

    @Override
    protected List<ForecastWeatherList> doInBackground(Context...params) 
        try 
            Log.d("debugMode", "The application is in doInBackground");

            URL url = new URL(serviceUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(15000 /* milliseconds */);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                // If the request was successful (response code 200),
                // then read the input stream and parse the response.
                if (urlConnection.getResponseCode() == 200) 
                    Log.e(TAG,"Response code:" + urlConnection.getResponseCode());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    ForecastWeatherListWrapper weatherWrapper = new Gson().fromJson(bufferedReader, ForecastWeatherListWrapper.class);
                    return weatherWrapper.getforecastWeatherLists();
                 else 
                    Log.e(TAG, "Error response code: " + urlConnection.getResponseCode());
                

         catch (Exception e) 

        


        return null;


    



    @Override
    protected void onPostExecute(List<ForecastWeatherList> result) 
        super.onPostExecute(result);
        if (result != null) 
            Log.e(TAG, "populate UI recycler view with gson converted data");
            listener.afterSearch(result);
        
    

这是我的日志: E/GetWeatherAync:响应代码:200

这是我的预报天气列表包装器:

 public class ForecastWeatherListWrapper 

 @SerializedName("list")
 @Expose
 private List<ForecastWeatherList> forecastWeatherLists;

 public List<ForecastWeatherList> getforecastWeatherLists() 
    return forecastWeatherLists;


public void setforecastWeatherLists(List<ForecastWeatherList>      
forecastWeatherItems)

   this.forecastWeatherLists = forecastWeatherItems;
       




public class ForecastWeatherList 
@SerializedName("dt")
@Expose
private Integer dt;
@SerializedName("main")
@Expose
private Main main;
@SerializedName("weather")
@Expose
private Weather weather = null;
@SerializedName("clouds")
@Expose
private Clouds clouds;
@SerializedName("wind")
@Expose
private Wind wind;
@SerializedName("rain")
@Expose
private Rain rain;
@SerializedName("sys")
@Expose
private Sys sys;
@SerializedName("dt_txt")
@Expose
private String dtTxt;

public Integer getDt() 
    return dt;


public void setDt(Integer dt) 
    this.dt = dt;


public Main getMain() 
    return main;


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


public Weather getWeather() 
    return (Weather) weather;


public void setWeather(Weather weather) 
    this.weather = weather;


public Clouds getClouds() 
    return clouds;


public void setClouds(Clouds clouds) 
    this.clouds = clouds;


public Wind getWind() 
    return wind;


public void setWind(Wind wind) 
    this.wind = wind;


public Rain getRain() 
    return rain;


public void setRain(Rain rain) 
    this.rain = rain;


public Sys getSys() 
    return sys;


public void setSys(Sys sys) 
    this.sys = sys;


public String getDtTxt() 
    return dtTxt;


public void setDtTxt(String dtTxt) 
    this.dtTxt = dtTxt;




  

这是我的一些用于解析 JSON 数据的 GSON 类。一些类是 Main、Clouds 等

这是我的主要课程:

public class Main 

@SerializedName("temp")
@Expose
private Double temp;
@SerializedName("temp_min")
@Expose
private Double tempMin;
@SerializedName("temp_max")
@Expose
private Double tempMax;
@SerializedName("pressure")
@Expose
private Double pressure;
@SerializedName("sea_level")
@Expose
private Double seaLevel;
@SerializedName("grnd_level")
@Expose
private Double grndLevel;
@SerializedName("humidity")
@Expose
private Integer humidity;
@SerializedName("temp_kf")
@Expose
private Integer tempKf;

public Double getTemp() 
    return temp;


    public void setTemp(Double temp) 
        this.temp = temp;
    

    public Double getTempMin() 
        return tempMin;
    

    public void setTempMin(Double tempMin) 
        this.tempMin = tempMin;
    

    public Double getTempMax() 
        return tempMax;
    

    public void setTempMax(Double tempMax) 
        this.tempMax = tempMax;
    

public Double getPressure() 
    return pressure;


public void setPressure(Double pressure) 
    this.pressure = pressure;


public Double getSeaLevel() 
    return seaLevel;


public void setSeaLevel(Double seaLevel) 
    this.seaLevel = seaLevel;


public Double getGrndLevel() 
    return grndLevel;


public void setGrndLevel(Double grndLevel) 
    this.grndLevel = grndLevel;


public Integer getHumidity() 
    return humidity;


public void setHumidity(Integer humidity) 
    this.humidity = humidity;


public Integer getTempKf() 
    return tempKf;


public void setTempKf(Integer tempKf) 
    this.tempKf = tempKf;


  

这是我的天气课:

public class Weather 

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("main")
@Expose
private String main;
@SerializedName("description")
@Expose
private String description;
@SerializedName("icon")
@Expose
private String icon;

public Integer getId() 
    return id;


public void setId(Integer id) 
    this.id = id;


public String getMain() 
    return main;


public void setMain(String main) 
    this.main = main;


public String getDescription() 
    return description;


public void setDescription(String description) 
    this.description = description;


public String getIcon() 
    return icon;


public void setIcon(String icon) 
    this.icon = icon;



  

这是我的原始字符串数据(我认为)。

 "cod":"200",
"message":0.0074,
  "cnt":39,
"list":[
  
     "dt":1534215600,
     "main":
        "temp":293.24,
        "temp_min":292.346,
        "temp_max":293.24,
        "pressure":1021.77,
        "sea_level":1028.21,
        "grnd_level":1021.77,
        "humidity":100,
        "temp_kf":0.89
     ,
     "weather":[
        
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10n"
        
     ],
     "clouds":
        "all":20
     ,
     "wind":
        "speed":2.51,
        "deg":275.001
     ,
     "rain":
        "3h":0.0050000000000008
     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-14 03:00:00"
  ,
  
     "dt":1534226400,
     "main":
        "temp":292.3,
        "temp_min":291.706,
        "temp_max":292.3,
        "pressure":1020.99,
        "sea_level":1027.42,
        "grnd_level":1020.99,
        "humidity":100,
        "temp_kf":0.6
     ,
     "weather":[
        
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        
     ],
     "clouds":
        "all":0
     ,
     "wind":
        "speed":2.52,
        "deg":294.505
     ,
     "rain":

     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-14 06:00:00"
  ,
  
     "dt":1534237200,
     "main":
        "temp":291.07,
        "temp_min":290.77,
        "temp_max":291.07,
        "pressure":1020.65,
        "sea_level":1027.03,
        "grnd_level":1020.65,
        "humidity":100,
        "temp_kf":0.3
     ,
     "weather":[
        
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        
     ],
     "clouds":
        "all":0
     ,
     "wind":
        "speed":1.31,
        "deg":225.5
     ,
     "rain":

     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-14 09:00:00"
  ,
  
     "dt":1534248000,
     "main":
        "temp":293.286,
        "temp_min":293.286,
        "temp_max":293.286,
        "pressure":1020.78,
        "sea_level":1027.17,
        "grnd_level":1020.78,
        "humidity":100,
        "temp_kf":0
     ,
     "weather":[
        
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"02d"
        
     ],
     "clouds":
        "all":8
     ,
     "wind":
        "speed":2.83,
        "deg":234.501
     ,
     "rain":

     ,
     "sys":
        "pod":"d"
     ,
     "dt_txt":"2018-08-14 12:00:00"
  ,
  
     "dt":1534258800,
     "main":
        "temp":298.671,
        "temp_min":298.671,
        "temp_max":298.671,
        "pressure":1020.76,
        "sea_level":1027.15,
        "grnd_level":1020.76,
        "humidity":92,
        "temp_kf":0
     ,
     "weather":[
        
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01d"
        
     ],
     "clouds":
        "all":0
     ,
     "wind":
        "speed":2.71,
        "deg":259.5
     ,
     "rain":

     ,
     "sys":
        "pod":"d"
     ,
     "dt_txt":"2018-08-14 15:00:00"
  ,
  
     "dt":1534269600,
     "main":
        "temp":300.7,
        "temp_min":300.7,
        "temp_max":300.7,
        "pressure":1019.76,
        "sea_level":1026.18,
        "grnd_level":1019.76,
        "humidity":83,
        "temp_kf":0
     ,
     "weather":[
        
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10d"
        
     ],
     "clouds":
        "all":24
     ,
     "wind":
        "speed":3.66,
        "deg":285.503
     ,
     "rain":
        "3h":1.11
     ,
     "sys":
        "pod":"d"
     ,
     "dt_txt":"2018-08-14 18:00:00"
  ,
  
     "dt":1534280400,
     "main":
        "temp":298.464,
        "temp_min":298.464,
        "temp_max":298.464,
        "pressure":1019.68,
        "sea_level":1025.97,
        "grnd_level":1019.68,
        "humidity":83,
        "temp_kf":0
     ,
     "weather":[
        
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10d"
        
     ],
     "clouds":
        "all":48
     ,
     "wind":
        "speed":3.27,
        "deg":289.504
     ,
     "rain":
        "3h":1.61
     ,
     "sys":
        "pod":"d"
     ,
     "dt_txt":"2018-08-14 21:00:00"
  ,
  
     "dt":1534291200,
     "main":
        "temp":297.882,
        "temp_min":297.882,
        "temp_max":297.882,
        "pressure":1020,
        "sea_level":1026.37,
        "grnd_level":1020,
        "humidity":82,
        "temp_kf":0
     ,
     "weather":[
        
           "id":500,
           "main":"Rain",
           "description":"light rain",
           "icon":"10n"
        
     ],
     "clouds":
        "all":36
     ,
     "wind":
        "speed":2.37,
        "deg":275.004
     ,
     "rain":
        "3h":0.13
     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-15 00:00:00"
  ,
  
     "dt":1534302000,
     "main":
        "temp":295.242,
        "temp_min":295.242,
        "temp_max":295.242,
        "pressure":1021.11,
        "sea_level":1027.53,
        "grnd_level":1021.11,
        "humidity":94,
        "temp_kf":0
     ,
     "weather":[
        
           "id":802,
           "main":"Clouds",
           "description":"scattered clouds",
           "icon":"03n"
        
     ],
     "clouds":
        "all":32
     ,
     "wind":
        "speed":1.26,
        "deg":313.002
     ,
     "rain":

     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-15 03:00:00"
  ,
  
     "dt":1534312800,
     "main":
        "temp":294.05,
        "temp_min":294.05,
        "temp_max":294.05,
        "pressure":1021.27,
        "sea_level":1027.77,
        "grnd_level":1021.27,
        "humidity":100,
        "temp_kf":0
     ,
     "weather":[
        
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        
     ],
     "clouds":
        "all":0
     ,
     "wind":
        "speed":2.46,
        "deg":274.504
     ,
     "rain":

     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-15 06:00:00"
  ,
  
     "dt":1534323600,
     "main":
        "temp":293.495,
        "temp_min":293.495,
        "temp_max":293.495,
        "pressure":1021.36,
        "sea_level":1027.7,
        "grnd_level":1021.36,
        "humidity":100,
        "temp_kf":0
     ,
     "weather":[
        
           "id":800,
           "main":"Clear",
           "description":"clear sky",
           "icon":"01n"
        
     ],
     "clouds":
        "all":0
     ,
     "wind":
        "speed":3.01,
        "deg":277.505
     ,
     "rain":

     ,
     "sys":
        "pod":"n"
     ,
     "dt_txt":"2018-08-15 09:00:00"
],
"city":
  "id":4347778,
  "name":"Baltimore",
  "coord":
     "lat":39.2909,
     "lon":-76.6108
  ,
  "country":"US",
  "population":620961
 
  

【问题讨论】:

或者这段代码返回 null return weatherWrapper.getforecastWeatherLists();? 【参考方案1】:

可能在您打印日志后,当您尝试转换 JSON 对象尝试在返回值之前打印日志时发生异常

Log.e("something",weatherWrapper.getforecastWeatherLists().size()+"")
   return weatherWrapper.getforecastWeatherLists();

很可能你有 JSON 转换异常

尝试登录catch看看发生了什么

catch (Exception e) 
    Log.e("catch","error")

        

【讨论】:

@ksb 请打印异常信息 这是我收到的异常消息:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 224 path $.list[0].weather @ksb 请告诉我你的 ForecastWeatherListWrapper 类也记录这个 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); Log.e("response",bufferedReader.toString) 我刚刚将包装代码添加到我原来的帖子的主体中。 请在 bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())) 之后添加 Log.e("response",bufferedReader.toString);【参考方案2】:

我认为问题出在您的网址上。你需要传递这样的参数,你忘记传递appid了吗? -

https://samples.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml&appid=b6907d289e10d714a6e88b30761fae22

您确定从 URL 获得正确的响应吗?如果是,请检查您的 AsyncTask 是否返回 null

 @Override
        protected void onPostExecute(List<ForecastWeatherList> result) 
            super.onPostExecute(result);
            if (result != null) 
                Log.e(TAG, "populate UI recycler view with gson converted data");
                listener.afterSearch(result);
             else
                Log.e(TAG, "Result is null");
                // check if this Log shows up?
           
        

更改您的服务网址

this.serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + "巴尔的摩" +"&appid="+api_key

【讨论】:

是的,我刚刚查过了。我的 logcat 中出现“结果为空”。【参考方案3】:

您的回复中的错误。 你的代码

ForecastWeatherListWrapper weatherWrapper = new Gson().fromJson(bufferedReader, ForecastWeatherListWrapper.class);

将响应转换为自定义对象。 所以响应必须以“”开头 但是您的响应以数组“[”

开头

您必须修复您的响应或使您的自定义对象期望像这样的数组

   Gson gson = new Gson();
        Type type = new TypeToken<List<ForecastWeatherListWrapper>>() 
        .getType();
        if (!bufferedReader.equals("")) 
         ForecastWeatherListWrapper weatherWrapper = gson.fromJson(bufferedReader, type);
        

【讨论】:

谢谢,但现在我得到:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ 你可以打印你的响应和 ForecastWeatherListWrapper 类你可以使用 POSTMAN 来读取响应

以上是关于片段中的 Asynctask 未到达 onPostExecute的主要内容,如果未能解决你的问题,请参考以下文章

等待多个AsyncTask完成

什么是生命周期感知方式来实现重复的AsyncTask?

从Asynctask ONPostExecute调用片段方法

如何从选项卡片段中的 AsyncTask Resftful WS 加载批量数据

Android ViewPager,片段中的cameraview未显示

在 AsyncTask 中将新的 TextView 设置为片段