【问题标题】:List remains empty even after being initialized即使初始化后列表仍然为空
【发布时间】:2015-08-04 21:56:34
【问题描述】:

对不起,如果标题有点抽象。我正在尝试从网站获取 JSON 代码并用它初始化一个列表。但是,由于某种原因,该列表仍然为空。我也是 Android 和 Java 的新手(从本周开始),因此非常感谢您的建议和批评!相关代码:

public class ForecastAdapter extends BaseAdapter {

    public static String CallURL(final String URL) {
        String line = "", all = "";
        URL myUrl = null;
        BufferedReader in = null;
        try {
            myUrl = new URL(URL);
            in = new BufferedReader(new InputStreamReader(myUrl.openStream()));

            while ((line = in.readLine()) != null)
                all += line;

        } catch (Exception e) {
            e.printStackTrace();}
        finally {
            if (in != null) {
                in.close();
            }
        }

        return all;
    }
    private List<ForecastDataSet> getDataForListView()
    {
    //ForecastDataSet is composed of 6 strings: Day, TempAvg, TempMin, TempMax, WeatherState and IconID
        List<ForecastDataSet> dataList = new ArrayList<ForecastDataSet>();
        String RawData = null;
        try {
        //Try to collect weather API data
            RawData = CallURL("http://api.openweathermap.org/data/2.5/forecast/daily?q=Berlin,de&units=metric&cnt=16");
        } catch (Exception e) {
            Log.e("Mini Weather Error", "CallURL method failed: " + e.getMessage());
        }
        //Parse RawData and extract necessary information
        JSONParser parser = new JSONParser();
        Object obj = null;
        try {
            obj = parser.parse(RawData);
            JSONObject jsonObject = (JSONObject) obj;
            //Iterate through the elements inside "list" in the JSON file
            ForecastDataSet data = new ForecastDataSet();
            JSONArray list = (JSONArray)jsonObject.get("list");
            Iterator i = list.iterator();

            //Fill the ForecastDataSet and add it to the bigger list (dataList)
            int increment = 0;
            while (i.hasNext()) {
                JSONObject innerObj = (JSONObject) i.next();
                JSONObject temps = (JSONObject) innerObj.get("temp");
                JSONArray tempList = (JSONArray) innerObj.get("weather");
                JSONObject weatherStatus = (JSONObject) tempList.get(0);
                data.Day = getDay(increment);
                data.TempAvg = ((String) temps.get("day")).split(".")[0] + " °C";
                data.TempMin = ((String) temps.get("min")).split(".")[0] + " °C";
                data.TempMax = ((String) temps.get("max")).split(".")[0] + " °C";
                data.WeatherState = (String) weatherStatus.get("main");
                data.IconID = (String) weatherStatus.get("icon");

                dataList.add(data);
                ++increment;
            }
            return dataList;
        } catch (Exception e) {
            Log.e("Mini Weather Error", "Error while filling ForecastData: " + e.getMessage());
        }
        return null;
    }

    //Here is the list that appears to be empty even after being initialized
    List<ForecastDataSet> ForecastData = getDataForListView();

    @Override
    public int getCount() {
    try {
        return ForecastData.size(); //-----> Always results in an error
    }
    catch (Exception e){
        Log.e("Mini Weather Error", "ForecastData is empty");
    }
        return 0;
    }

    @Override
    public ForecastDataSet getItem(int position) {
        try {
            return ForecastData.get(position); //-----> Always results in an error
        }
            catch (Exception e){
                Log.e("Mini Weather Error", "ForecastData is empty");
            }
            return null;
    }

    @Override
    public long getItemId(int position)
    {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try{
        if(convertView==null) {

            LayoutInflater inflater = (LayoutInflater) LayoutInflater.from(parent.getContext());
            View rowView = inflater.inflate(R.layout.list_item, parent, false);
        }

     //Fill a list item view and return it
            TextView dayOfTheWeek = (TextView)convertView.findViewById(R.id.listItemDate);
            TextView description = (TextView)convertView.findViewById(R.id.weather_info);
            ImageView icon = (ImageView) convertView.findViewById(R.id.weatherIconItem);
            ForecastDataSet currentData;
            currentData = ForecastData.get(position);
            dayOfTheWeek.setText(currentData.Day);
            String fullDescription;
            fullDescription = currentData.TempAvg + "\n\n" +
                    "Min: " + currentData.TempMin + "\n" +
                    "Max: " + currentData.TempMax;
            description.setText(fullDescription);

            return convertView;
        }
        catch (Exception ex)
        {
            Log.e("Mini Weather Error", "Something went wrong when creating the view, error message: \n" + ex.getMessage());
        }
       return null;
    }
}

【问题讨论】:

  • 将 System.out.println() 语句添加到您的 while 循环中,以查看其中的代码是否实际执行。如果列表总是返回空,那么很可能 while 循环永远不会被执行!
  • 您的日志中有什么内容?
  • @PM77-1 在打开应用程序后,我总是收到大约 9-10 次“ForecastData 为空”。艾伦感谢您的提示,我会尝试的。
  • 从主线程网络访问被禁止启动 android 4 (?)。还要检查清单中的网络许可。

标签: java android listview getjson


【解决方案1】:

因为,

List<ForecastDataSet> ForecastData = getDataForListView();

除非getDataForListView() 是静态函数,否则此行从未初始化ForecastData 列表。所以

创建ForecastAdapter构造函数,并在其中调用getDataForListView();

喜欢,

public class ForecastAdapter extends BaseAdapter {

  List<ForecastDataSet> ForecastData;

  public ForecastAdapter ()
  {
    //Here is the list that appears to be empty even after being initialized
    ForecastData = getDataForListView();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    相关资源
    最近更新 更多