将JSONArray放入列表(Android)

将JSONArray放入列表(Android),android,android-json,Android,Android Json,我有一个项目,可以接受一个JSONObject并将其放入edittext,但我正试图找出如何更改它,以便它接受一个JSONArray并将其放入listView 这是我目前的代码: public class Js extends Activity { private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=chicago"; //private String url1 = "http://bisonsoft

我有一个项目,可以接受一个JSONObject并将其放入edittext,但我正试图找出如何更改它,以便它接受一个JSONArray并将其放入listView

这是我目前的代码:

public class Js extends Activity {


private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=chicago";
//private String url1 = "http://bisonsoftware.us/hhs/messages.json";
private TextView temperature;//,country,temperature,humidity,pressure;
private HandleJSON obj;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_js);
    //location = (EditText)findViewById(R.id.editText1);
    //country = (TextView)findViewById(R.id.editText2);
    temperature = (TextView)findViewById(R.id.editText3);
    //humidity = (EditText)findViewById(R.id.editText4);
    //pressure = (EditText)findViewById(R.id.editText5);
}

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

public void open(View view){
    //String url = location.getText().toString();
    //String finalUrl = url1 + url;
    //country.setText(url1);
    obj = new HandleJSON(url1);
    obj.fetchJSON();

    while(obj.parsingComplete);
    //country.setText(obj.getCountry());
    temperature.setText(obj.getTemperature());
    //humidity.setText(obj.getHumidity());
    //pressure.setText(obj.getPressure());

}
}

public class HandleJSON {

//private String country = "temperature";
private String temperature = "clouds";
//private String humidity = "humidity";
//private String pressure = "pressure";
private String urlString = null;

public volatile boolean parsingComplete = true;
public HandleJSON(String url){
    this.urlString = url;
}
/*public String getCountry(){
    return country;
}*/
public String getTemperature(){
    return temperature;
}
/*public String getHumidity(){
    return humidity;
}
public String getPressure(){
    return pressure;
}*/

@SuppressLint("NewApi")
public void readAndParseJSON(String in) {
    try {
        JSONObject reader = new JSONObject(in);

        //JSONObject sys  = reader.getJSONObject("main");
        //country = sys.getString("temp");

        JSONObject main  = reader.getJSONObject("clouds");
        temperature = main.getString("all");


        //pressure = main.getString("pressure");
        //humidity = main.getString("humidity");

        parsingComplete = false;



    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public void fetchJSON(){
    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                InputStream stream = conn.getInputStream();

                String data = convertStreamToString(stream);

                readAndParseJSON(data);
                stream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
}
static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
}
我已经尝试了一段时间,但是没有找到一个好的方法来通过解析数据的方式来实现。提前感谢您提供的任何帮助

以下是JSON:

"messages":["This is a demo message.  Enjoy!","Another demonstration message stored in JSON format.","JSON stands for JavaScript Object Notation (I think)"]

你真正要问的是几个问题。你自己把它分解一下,我想你会过得轻松得多

  • 创建执行internet服务请求并返回响应、处理错误情况等的功能

  • 创建一个反映JSON内容的“Weather”类(例如,对于您的类,包含温度、压力、湿度等)

  • 创建检查响应有效性并从中构造天气对象的功能

  • 从响应中创建这些天气对象(列表、集合等)的集合

  • 创建一个自定义ListAdapter,它获取天气对象的实例并将其转换为UI

  • 利润

  • 单独来看,您将更容易处理此问题。自定义适配器的实现非常简单。那么,假设你有一个简单的天气课,像这样:

    public final class Weather {
        public final String temperature;
        public final String pressure;
        public final String humidity;
    
        public Weather(String temperature, String pressure, String humidity) {
            this.temperature = temperature;
            this.pressure = pressure;
            this.humidity = humidity;
        }
    
        public static Weather valueOf(JSONObject json) throws JSONException {
            String temperature = json.getString("temp");
            String pressure = json.getString("pressure");
            String humidity = json.getString("humidity");
        }
    }
    
    BaseAdapter
    创建一个简单的子类,它接受您的
    Weather
    并将其调整为您创建的自定义布局:

    public final class WeatherAdapter extends BaseAdapter {
        private final List<Weather> mWeatherList;
        private final LayoutInflater mInflater;
    
        public WeatherAdapter(Context ctx, Collection<Weather> weather) {
            mInflater = LayoutInflater.from(ctx);
            mWeatherList = new ArrayList<>();
            mWeatherList.addAll(weather);
        }
    
        @Override public int getCount() {
            // Return the size of the data set
            return mWeatherList.size();
        }
    
        @Override public Weather getItem(int position) {
            // Return the item in our data set at the given position
            return mWeatherList.get(position);
        }
    
        @Override public long getItemId(int position) {
            // Not useful in our case; just return position
            return position;
        }
    
        @Override public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                // There's no View to re-use, inflate a new one.
                // This assumes you've created a layout "weather_list_item.xml"
                // with textviews for pressure, temperature, and humidity
                convertView = mInflater.inflate(R.layout.weather_list_item, parent, false);
    
                // Cache the Views we get with findViewById() for efficiency
                convertView.setTag(new WeatherViewHolder(convertView));
            }
    
            // Get the weather item for this list position
            Weather weather = getItem(position);
            WeatherViewHolder holder = (WeatherViewHolder) convertView.getTag();
    
            // Assign text, icons, etc. to your layout
            holder.pressure.setText(weather.pressure);
            holder.temperature.setText(weather.temperature);
            holder.humidity.setText(weather.humidity);
    
            return convertView;
        }
    
        public static class WeatherViewHolder {
            public final TextView pressure;
            public final TextView humidity;
            public final TextView temperature;
    
            public WeatherViewHolder(View v) {
                pressure = (TextView) v.findViewById(R.id.pressure);
                humidity = (TextView) v.findViewById(R.id.humidity);
                temperature = (TextView) v.findViewById(R.id.temperature);
            }
        }
    }
    
    公共最终类WeatherAdapter扩展了BaseAdapter{
    私人最终名单mWeatherList;
    私人最终布局平面图;
    公共天气适配器(上下文ctx、集合天气){
    mInflater=LayoutInflater.from(ctx);
    mWeatherList=新的ArrayList();
    mWeatherList.addAll(天气);
    }
    @重写公共int getCount(){
    //返回数据集的大小
    返回mWeatherList.size();
    }
    @覆盖公共天气getItem(内部位置){
    //在给定位置返回数据集中的项
    返回mWeatherList.get(位置);
    }
    @覆盖公共长getItemId(int位置){
    //在我们的情况下没有用处;只返回位置
    返回位置;
    }
    @覆盖公共视图getView(int位置、视图转换视图、视图组父视图){
    if(convertView==null){
    //没有重新使用的观点,膨胀一个新的。
    //这假设您已经创建了布局“weather\u list\u item.xml”
    //具有压力、温度和湿度的文本视图
    convertView=mInflater.充气(R.layout.weather\u list\u项,父项,false);
    //缓存使用findViewById()获得的视图以提高效率
    setTag(新WeatherViewHolder(convertView));
    }
    //获取此列表位置的天气项目
    天气=获取项目(位置);
    WeatherViewHolder=(WeatherViewHolder)convertView.getTag();
    //为布局指定文本、图标等
    保持架压力设置文本(天气压力);
    holder.temperature.setText(天气温度);
    保持架.湿度.设置文本(天气.湿度);
    返回视图;
    }
    公共静态类WeatherViewHolder{
    公众舆论压力;
    公共最终文本视图湿度;
    公共最终文本视图温度;
    公共天气视图支架(视图v){
    压力=(文本视图)v.findviewbyd(R.id.pressure);
    湿度=(文本视图)v.findviewbyd(R.id.湿度);
    温度=(文本视图)v.findviewbyd(R.id.temperature);
    }
    }
    }
    
    < /代码> 首先,考虑将< <代码> JSONArray <代码>更改为<代码>字符串[]/COD>。查看以下代码块以获取示例:

    String[] jsonMessages = jsonArrayToStringArray(yourJsonArray);
    
    public String[] jsonArrayToStringArray(JSONArray arr){
        List<String> list = new ArrayList<String>();
        for(int i = 0; i < arr.length(); i++){
            list.add(arr.getJSONObject(i).getString("name"));
        }
        return list.toArray(new String[list.size()]);
    }
    

    在这个
    ArrayAdapter
    中,您使用的是预先创建的布局(这是非常基本的)。要为
    列表视图的每个元素创建更高级的视图,您需要制作一个自定义适配器。

    所以您想在列表视图中显示文本??like 1st item=这是一条演示消息。祝你愉快!。第2项=另一个以JSON格式存储的演示消息。你想要listview吗?是的,完全一样。你的问题是什么?如何解析JSON数据或如何将解析后的数据添加到列表中?你试过什么?列表在哪里?此url为“”。这只去芝加哥。正确的?如果我理解正确,您需要一个列表视图,其中每个元素都有城市名称和天气详细信息(温度、预确认、日出…)。或者你想显示一个只包含城市名称的列表,当用户点击一个城市时,一个新的活动将打开,他可以在那里看到关于该城市的所有详细信息?你想走哪条路?
    ListView myListView = (ListView) findViewById(R.id.my_list_view);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, jsonMessages);
    myListView.setAdapter(adapter);