在网格视图中解析JSON数据

时间:2013-09-25 19:27:10

标签: java android json gridview

我想用JSON链接中的数据填充gridview。如何在检索数据后填充gridview。 它基本上适用于天气应用程序。

这是我的JSON解析器类:

public class JSONWeatherParser {

public static WeatherForecast getForecastWeather(String data) throws JSONException  {

    WeatherForecast forecast = new WeatherForecast();

    // We create out JSONObject from the data
    JSONObject jObj = new JSONObject(data);

    JSONArray jArr = jObj.getJSONArray("list"); // Here we have the forecast for every day

    // We traverse all the array and parse the data
    for (int i=0; i < jArr.length(); i++) {
        JSONObject jDayForecast = jArr.getJSONObject(i);

        // Now we have the json object so we can extract the data
        DayForecast df = new DayForecast();

        // We retrieve the timestamp (dt)
        df.timestamp = jDayForecast.getLong("dt");

        // Temp is an object
        JSONObject jTempObj = jDayForecast.getJSONObject("temp");

        df.forecastTemp.day = (float) jTempObj.getDouble("day");
        df.forecastTemp.min = (float) jTempObj.getDouble("min");
        df.forecastTemp.max = (float) jTempObj.getDouble("max");
        df.forecastTemp.night = (float) jTempObj.getDouble("night");
        df.forecastTemp.eve = (float) jTempObj.getDouble("eve");
        df.forecastTemp.morning = (float) jTempObj.getDouble("morn");

        // Pressure & Humidity
        df.weather.currentCondition.setPressure((float) jDayForecast.getDouble("pressure"));
        df.weather.currentCondition.setHumidity((float) jDayForecast.getDouble("humidity"));

        // ...and now the weather
        JSONArray jWeatherArr = jDayForecast.getJSONArray("weather");
        JSONObject jWeatherObj = jWeatherArr.getJSONObject(0);
        df.weather.currentCondition.setWeatherId(getInt("id", jWeatherObj));
        df.weather.currentCondition.setDescr(getString("description", jWeatherObj));
        df.weather.currentCondition.setCondition(getString("main", jWeatherObj));
        df.weather.currentCondition.setIcon(getString("icon", jWeatherObj));

        forecast.addForecast(df);
    }



    return forecast;
}   


private static JSONObject getObject(String tagName, JSONObject jObj)  throws JSONException {
    JSONObject subObj = jObj.getJSONObject(tagName);
    return subObj;
}

private static String getString(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getString(tagName);
}

private static float  getFloat(String tagName, JSONObject jObj) throws JSONException {
    return (float) jObj.getDouble(tagName);
}

private static int  getInt(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getInt(tagName);
}

}

GridViewAdapter类:

public class GridViewAdapter extends BaseAdapter {
private Context mContext;
private int numDays;
private WeatherForecast forecast;
private final static SimpleDateFormat sdf = new SimpleDateFormat("E, dd-MM");
private DayForecast dayForecast;
private ImageView iconWeather;

public GridViewAdapter(int numDays, WeatherForecast forecast) {
    this.numDays = numDays;
    this.forecast = forecast;
}

public int getCount() {
    return numDays;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    //ImageView imageView;
    //ImageView icon;
    TextView temp;
    TextView date;


    if (convertView == null) {  // if it's not recycled, initialize some attributes


        //icon = new ImageView(mContext);
        temp = new TextView(mContext);
        date = new TextView(mContext);

        LayoutInflater inflater = (LayoutInflater)   mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.grid_icon, parent, false);

    }



    temp=(TextView)convertView.findViewById(R.id.text);
    temp.setText( (int) (dayForecast.forecastTemp.min - 275.15) + "-" + (int) (dayForecast.forecastTemp.max - 275.15) );
    date=(TextView)convertView.findViewById(R.id.date);
    date.setText(DateUtils.formatDateTime(mContext, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE ));

    return convertView;
    //JSONIconWeatherTask task = new JSONIconWeatherTask();
    //task.execute(new String[]{dayForecast.weather.currentCondition.getIcon()});

    /*imageView.setImageResource(mThumbIds[position]);*/
    //return imageView;
}
public void setForecast(DayForecast dayForecast) {

    this.dayForecast = dayForecast;

}

我的AsyncTask:

private class JSONForecastWeatherTask extends AsyncTask<String, Void, WeatherForecast> {

    @Override
    protected WeatherForecast doInBackground(String... params) {

        String data = ( (new WeatherHttpClient()).getForecastWeatherData(params[0], params[1], params[2]));
        WeatherForecast forecast = new WeatherForecast();
        try {
            forecast = JSONWeatherParser.getForecastWeather(data);
            System.out.println("Weather ["+forecast+"]");

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

}

@Override
    protected void onPostExecute(WeatherForecast forecastWeather) {         
        super.onPostExecute(forecastWeather);
        GridView gridView;
        gridView = (GridView) findViewById(R.id.gridview);

        gridView.setAdapter(new GridViewImageAdapter(Integer.parseInt(forecastDaysNum), forecastWeather));
    }

} 的 LOG

  

09-27 00:03:10.132:E / AndroidRuntime(29848):致命异常:主要   09-27 00:03:10.132:E / AndroidRuntime(29848):java.lang.NullPointerException   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.app.Activity.findViewById(Activity.java:1843)   09-27 00:03:10.132:E / AndroidRuntime(29848):at com.example.weatherforecast.MainActivity $ JSONForecastWeatherTask.onPostExecute(MainActivity.java:205)   09-27 00:03:10.132:E / AndroidRuntime(29848):at com.example.weatherforecast.MainActivity $ JSONForecastWeatherTask.onPostExecute(MainActivity.java:1)   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.os.AsyncTask.finish(AsyncTask.java:631)   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.os.AsyncTask.access $ 600(AsyncTask.java:177)   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:644)   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.os.Handler.dispatchMessage(Handler.java:99)   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.os.Looper.loop(Looper.java:137)   09-27 00:03:10.132:E / AndroidRuntime(29848):在android.app.ActivityThread.main(ActivityThread.java:5234)   09-27 00:03:10.132:E / AndroidRuntime(29848):at java.lang.reflect.Method.invokeNative(Native Method)   09-27 00:03:10.132:E / AndroidRuntime(29848):at java.lang.reflect.Method.invoke(Method.java:525)   09-27 00:03:10.132:E / AndroidRuntime(29848):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:799)   09-27 00:03:10.132:E / AndroidRuntime(29848):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)   09-27 00:03:10.132:E / AndroidRuntime(29848):at dalvik.system.NativeStart.main(Native Method)

我还是Java的初学者。

1 个答案:

答案 0 :(得分:0)

我没有看到GridView适配器的代码。首先,您应该为GridView编写一个单独的类 - 适配器,其中必须覆盖方法 getView()(请参阅有关GridView适配器的类似问题)。当您检索数据时,您应该为您的适配器调用notifyDataSetChanged()方法 - 这将使用新数据刷新GridView。

如何自定义gridview http://www.mkyong.com/android/android-gridview-example/

的好示例

不要忘记调用 adapter.notifyDataSetChanged();