我有一个可以将JSONObject放入一个编辑文本的项目,但是我试图弄清楚如何对其进行更改,以便它可以将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)"]

最佳答案

您真正要问的是几个问题。自己动手,我想您会轻松得多。


创建执行互联网服务请求并返回响应,处理错误情况等的功能。
创建一个反映JSON内容的“天气”类(例如,针对您的类,包含温度,压力,湿度等的类)
创建检查响应的有效性并从中构造Weather对象的功能。
从响应中创建这些天气对象(列表,集合等)的集合
创建一个自定义ListAdapter,它接受Weather对象的实例并将其转换为UI。
???
利润


单独考虑,您将可以更轻松地解决此问题。自定义适配器很容易实现。因此,假设您有一个简单的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);
        }
    }
}

关于android - 将JSONArray放入列表(Android),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24376346/

10-09 07:41