JSON 解析为 ListView

JSON Parsing Into ListView

我正在尝试将 JSON 数据解析到我的 ListView。问题是 我的 JSON; 没有任何 URL 所以,我为此创建了一个如下:

{ 
    "items": [ 
        { 
            "Image": "http://camranger.com/wp-content/uploads/2014/10/Android-Icon.png", 
            "title": "Item1",
            "offer": "2x1", 
            "cost": "€10",
            "end_date": "12-9-2015" 
        }, 
        { 
            "Image": "http://camranger.com/wp-content/uploads/2014/10/Android-Icon.png", 
            "title": "Item2",
            "offer": "gratis", 
            "cost": "€20", 
            "end_date": "12-9-2015" 
        }, 
        { 
            "Image": "http://camranger.com/wp-content/uploads/2014/10/Android-Icon.png", 
            "title": "Item3",
            "offer": "40x1",
            "cost": "€30", 
            "end_date": "12-9-2015" 
        } 
    ] 
}

现在,我只需要把它放在我的 ListView 上。我创建了一个 class (JSONParser) 如下:

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {}

    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

所以,我被困在我试图放置 JSON 数据的地方(在 JSONParser class) 我不知道我应该做什么。

目前我试过的写在下面:

//JSON
// url to make request
private static String url = "";

// JSON Node names
private static final String TAG_Items = "items";
private static final String TAG_Image = "Image";
private static final String TAG_title = "title";
private static final String TAG_offer = "offer";
private static final String TAG_cost = "cost";
private static final String TAG_enddate = "end_date";

// contacts JSONArray
JSONArray ofertas = null;

在 url 上,我没有放任何东西,因为我没有 URL,我有一个 assets 文件夹 JSON 但我不知道它是否有效...

我从 JSONParser class 创建了一个实例,我得到了 JSON URL 个字符串。此外,我创建了一个遍历所有项目的循环,用于将每个 JSON 项目存储在变量中。

现在,我卡住了,无法找到将这些数据放入我的 ListView 的方法。另外因为我不能做测试... :(

JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        ofertas = json.getJSONArray(TAG_Items);
        for(int i = 0; i < ofertas.length(); i++){
            JSONObject c = ofertas.getJSONObject(i);
            String image = c.getString(TAG_Image);
            String title = c.getString(TAG_title);
            String offer = c.getString(TAG_offer);
            String cost = c.getString(TAG_cost);
            String enddate = c.getString(TAG_enddate);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

我的ListView有一个例子没有JSON数据如下:

mItems = new ArrayList<ListViewItem>();
Resources resources = getResources();
mItems.add(new ListViewItem(resources.getDrawable(R.drawable.zumo_oferta), getString(R.string.pew), getString(R.string.pew_precio), getString(R.string.pew_descuento), getString(R.string.pew_data)));
setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));

提前致谢。

编辑

我已经有一个ListViewItem,你可以在下面看到它的相关代码行:

public class ListViewItem {
    public final Drawable icon;       // the drawable for the ListView item ImageView
    public final String title;       // the text for the ListView item title
    public final String precio;      // the price for the ListView item
    public final String descuento;   // the price for the discount for the ListView item
    public final String date;        //the date for the sale for the ListView item
     // the text for the ListView item description

    public ListViewItem(Drawable icon, String title, String precio, String descuento, String date) {
        this.icon = icon;
        this.title = title;
        this.precio = precio;
        this.descuento = descuento;
        this.date = date;
    }
}

ListViewDemoAdapter的代码行如下:

public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> {
    public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
        super(context, R.layout.listview_item, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;

        if(convertView == null) {
            // inflate the GridView item layout
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.listview_item, parent, false);

            // initialize the view holder
            viewHolder = new ViewHolder();
            viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
            viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
            viewHolder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
            viewHolder.tvDiscount = (TextView) convertView.findViewById(R.id.tvDiscount);
            viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDatas);
            convertView.setTag(viewHolder);
        } else {
            // recycle the already inflated view
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // update the item view
        ListViewItem item = getItem(position);
        viewHolder.ivIcon.setImageDrawable(item.icon);
        viewHolder.tvTitle.setText(item.title);
        viewHolder.tvDiscount.setText(item.descuento);
        viewHolder.tvPrice.setText(item.precio);
        viewHolder.tvDate.setText(item.date);

        return convertView;
    }

    private static class ViewHolder {
        ImageView ivIcon;
        TextView tvTitle;
        TextView tvDiscount;
        TextView tvPrice;
        TextView tvDate;
    }
}

编辑2

现在,我要做的是:

    public class MisOfertasFragment extends ListFragment {
    private List<ListViewItem> mItems;        // ListView items list
    private Menu optionsMenu;
    public MisOfertasFragment(){}
    ProgressDialog progress;

    //COSAS DEL JSON

    // url to make request
    private static String url = "file:///C:/Users/Skizo/Desktop/jsontest.html";

    // JSON Node names
    private static final String TAG_Items = "items";
    private static final String TAG_Image = "Image";
    private static final String TAG_title = "title";
    private static final String TAG_offer = "offer";
    private static final String TAG_cost = "cost";
    private static final String TAG_enddate = "end_date";


    // contacts JSONArray
    JSONArray ofertas = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        //JSON stuff
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

// getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        if (response != "" || response != null) {
            try {

                ArrayList<HashMap<String, String>> map = new ArrayList<HashMap<String, String>>();

                JSONObject Obj = new JSONObject(response); //here will be your complete String from the assest folder

                JSONArray items = Obj.getJSONArray("items");

                for (int i = 0; i < items.length(); i++) {

                    HashMap<String, String> hmap = new HashMap<String, String>();

                    JSONObject c = items.getJSONObject(i);

                    String image = c.getString("Image");
                    String title = c.getString("title");
                    String offer = c.getString("offer");
                    String cost = c.getString("cost");
                    String end_date = c.getString("end_date");

                    hmap.put("image", image);
                    hmap.put("title", title);
                    hmap.put("offer", offer);
                    hmap.put("cost", cost);
                    hmap.put("end_date", end_date);

                    map.add(hmap);

                }

            } catch (JSONException e) {

                e.printStackTrace();

            }
        }
        // initialize the items list

        progress = ProgressDialog.show(getActivity(), "Cargando",
                "Espere mientras cargan sus ofertas", true);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);


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

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mItems = new ArrayList<ListViewItem>();
                        Resources resources = getResources();



                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.zumo_oferta), getString(R.string.pew), getString(R.string.pew_precio), getString(R.string.pew_descuento), getString(R.string.pew_data)));


                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.sopa_oferta), getString(R.string.bebo), getString(R.string.bebo_precio), getString(R.string.bebo_descuento), getString(R.string.bebo_data)));
                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.tomate_oferta), getString(R.string.aim), getString(R.string.aim_precio), getString(R.string.aim_descuento), getString(R.string.aim_data)));

                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.levadura_oferta), getString(R.string.youtube), getString(R.string.youtube_precio), getString(R.string.youtube_descuento), getString(R.string.youtube_data)));

                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.tomate_oferta), getString(R.string.aim), getString(R.string.aim_precio), getString(R.string.aim_descuento), getString(R.string.aim_data)));
                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.tomate_oferta), getString(R.string.aim), getString(R.string.aim_precio), getString(R.string.aim_descuento), getString(R.string.aim_data)));

                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.levadura_oferta), getString(R.string.youtube), getString(R.string.youtube_precio), getString(R.string.youtube_descuento), getString(R.string.youtube_data)));

                        mItems.add(new ListViewItem(resources.getDrawable(R.drawable.tomate_oferta), getString(R.string.aim), getString(R.string.aim_precio), getString(R.string.aim_descuento), getString(R.string.aim_data)));
                        // initialize and set the list adapter
                        setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
                        progress.dismiss();

                    }
                });
            }

        }).start();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // remove the dividers from the ListView of the ListFragment
        getListView().setDivider(null);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // retrieve theListView item
        ListViewItem item = mItems.get(position);

        // do something
        Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.search_view,menu );
        inflater.inflate(R.menu.refresh_menu, menu);
    }

}

还有我自己放的数据(我不要的东西),在url上放了一个我自己创建的html(不知道是不是它有效)并且我已经实现了 HashMap,但我根本没有完成。

你快到了。您需要一个代表 信息 的 class,它通常是模型的一部分。我们称之为 class Product,

 public class Product {
      String image;
      String title;
      String offer;
      String cost;
      String enddate;
 }

然后声明一个 ArrayList<Product>,在循环的每次迭代中,创建一个 Product 的实例,填充它,并将其添加到 ArrayList

try {
    ArrayList<Product> items = new ArrayList<>();
    ofertas = json.getJSONArray(TAG_Items);
    for(int i = 0; i < ofertas.length(); i++){
        JSONObject c = ofertas.getJSONObject(i);
        Product p = new Product();
        p.image = c.getString(TAG_Image);
        p.title = c.getString(TAG_title);
        p.offer = c.getString(TAG_offer);
        p.cost = c.getString(TAG_cost);
        p.enddate = c.getString(TAG_enddate);
        mItems.add(p);
     }
} catch (JSONException e) {
    e.printStackTrace();
}