【问题标题】:Parsing JSON data and storing into a listview解析 JSON 数据并存储到列表视图中
【发布时间】:2015-12-04 16:33:41
【问题描述】:

我目前正在开发一个小型安卓天气应用程序。它通过 3 个字符串来显示来自开源 weatherAPI 的三个天气元素。我试图在listview 中显示它。传入 1 个字符串时,我得到了它的工作。但是我在传递多个字符串时遇到了麻烦。任何建议将不胜感激

ArrayList<Weather> weatherData = new ArrayList<Weather>();
    private ListView listView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView1 = (ListView) findViewById(R.id.listView1);
        String[] city = {
                new String("dublin,ire"),
                new String("London,uk")

        };
        for (int i = 0; i < city.length; ++i) {
            listView1.add(city[i]);
        }

        //String city2 = "Dublin,ire";
        Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {

                                       public void onClick(View v) {
                                           setContentView(R.layout.activity_main);
                                           Button button1 = (Button) findViewById(R.id.button1);
                                           Log.d("MR.bool", "Button1 was clicked ");

                                           startActivity(new Intent(MainActivity.this, WebViewActivity.class));
                                       }
                                   });


                cityText = (TextView) findViewById(R.id.cityText);
                condDescr = (TextView) findViewById(R.id.condDescr);
                temp = (TextView) findViewById(R.id.temp);
                hum = (TextView) findViewById(R.id.hum);
                press = (TextView) findViewById(R.id.press);
                windSpeed = (TextView) findViewById(R.id.windSpeed);
                windDeg = (TextView) findViewById(R.id.windDeg);
                imgView = (ImageView) findViewById(R.id.condIcon);
                imgView2 = (ImageView) findViewById(R.id.imageView1);


                JSONWeatherTask task = new JSONWeatherTask();
                task.execute(new String[]{city});

                if (city.contains("uk")) {
                    imgView2.setImageResource(R.drawable.uk);
                } else if (city.contains("ire")) {
                    imgView2.setImageResource(R.drawable.ireland);
                } else if (city.contains("de")) {
                    imgView2.setImageResource(R.drawable.germany);
                }
            }





            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }


            private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

                @Override
                protected Weather doInBackground(String... params) {
                    Weather weather = new Weather();
                    String data = ((new WeatherHttpClient()).getWeatherData(params[0]));

                    try {
                        weather = JSONWeatherParser.getWeather(data);

                        // Let's retrieve the icon
                        weather.iconData = ((new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return weather;

                }






                @Override
                protected void onPostExecute(Weather weather) {
                    super.onPostExecute(weather);

                    if (weather.iconData != null && weather.iconData.length > 0) {
                        Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
                        imgView.setImageBitmap(img);
                    }

                    else if(weatherData.size() > 0)
                    {
                        ArrayAdapter<Weather> adapter = new ArrayAdapter<Weather>(MainActivity.this,
                                android.R.layout.activity_list_item, weatherData);

                        listView1.setAdapter(adapter);

                        // here you can also define your custom adapter and set it to listView
                        //according to your own defined layout as items
                    }

                    cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
                    condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
                    temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
                    hum.setText("" + weather.currentCondition.getHumidity() + "%");
                    press.setText("" + weather.currentCondition.getPressure() + " hPa");
                    windSpeed.setText("" + weather.wind.getSpeed() + " mps");
                    windDeg.setText("" + weather.wind.getDeg() + "�");

                }


            }
        }

【问题讨论】:

  • 请详细描述“问题”。
  • 您好,感谢您的回复。我试图传递 3 个字符串(位置,例如“伦敦,英国”,巴黎,法国和柏林,dn)来获取在列表视图中同时显示天气数据的解析对象。我目前只能传递 1 个字符串,它显示 1 个单独的天气对象。所以总的麻烦不是只传入 1 个字符串,我只想用一个数组一次完成解析 3 个天气对象。我对android足够新,我希望我能更详细地解释一下。谢谢。
  • 让我们看看你的适配器。你应该在你的 ArrayList 中添加你的城市,而不是在视图中。
  • 查看link

标签: android json string listview android-arrayadapter


【解决方案1】:

您可以使用 Gson 来解析 json。 我假设您正在接收一个 jsonArray。所以,你可以这样做:

ArrayList<Weather> weatherArrayList = new ArrayList<Weather>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray jArray = jsonParser.parse(responseStr).getAsJsonArray();

for (JsonElement obj : jArray) {
   Weather weatherModel = gson.fromJson(response, Weather.class);
   weatherArrayList.add(weatherModel);
}

上面的代码解析你的json中的数据并将它们添加到你的“weatherArrayList”这个ArrayList中,你应该把它放在你的适配器中,然后在你的listview中设置。

这可能是您的自定义适配器

public class WeatherAdapter extends ArrayAdapter<Weather> {

    public WeatherAdapter(Context context) {
        super(context, 0);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
       // here you should set up the custom view. That is the view of each Item of your ListView

    }
}

希望对你有所帮助:)

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2017-07-21
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多