简体   繁体   English

列表即使初始化后仍然为空

[英]List remains empty even after being initialized

Sorry if the title is a bit abstract. 抱歉,标题有点抽象。 I am trying to get JSON code from a website and initialize a list with it. 我正在尝试从网站获取JSON代码并使用它初始化列表。 However, the list remains empty for some reason. 但是,由于某些原因,该列表仍然为空。 I am also a newbie in Android and Java (literally started this week), so advice and critics are appreciated! 我还是Android和Java的新手(本周从字面上开始),因此建议和批评者都感激不尽! Relevant code: 相关代码:

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;
    }
}

Because, 因为,

List<ForecastDataSet> ForecastData = getDataForListView();

this line never initialized ForecastData List unless getDataForListView() is static function. 除非getDataForListView()是静态函数,否则此行不会初始化ForecastData列表。 So 所以

Create a Constructor of ForecastAdapter and call getDataForListView(); 创建ForecastAdapter构造方法并调用getDataForListView(); in it. 在里面。

Like, 喜欢,

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();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM