将JSONArray放入列表(Android)

时间:2014-06-23 23:51:58

标签: 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://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)"]

2 个答案:

答案 0 :(得分:1)

你真正要问的是几个问题。为自己分解,我认为你会有更轻松的时间。

  1. 创建执行互联网服务请求并返回响应,处理错误案例等的功能。

  2. 创建一个"天气"反映JSON内容的类(例如,对于你的,有温度,压力,湿度等的类)

  3. 创建检查响应有效性的功能,并从中构建Weather对象。

  4. 从回复中创建这些天气对象(列表,集等)的集合

  5. 创建一个自定义ListAdapter,它接受Weather对象的一个​​实例并将其转换为UI。

  6. ???

  7. 利润

  8. 单独来看,你可以更轻松地解决这个问题。自定义适配器实现起来非常简单。所以,假设你有一个像这样的简单Weather类:

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

答案 1 :(得分:0)

首先,考虑将您的JSONArray更改为String[]。请查看以下代码块以获取示例:

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

接下来,既然您已经拥有String[],就可以为ListView构建一个适配器,并使用数组填充ListView

首先,您必须获得布局中包含的ListView。然后,您可以构建一个简单的适配器,最后,您必须将ListView的适配器设置为适配器。例如:

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

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