Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20616

JSON Parsing Into ListView

I'm trying to parsing the JSON data to my ListView. The problem is that I don't have any URL with my JSON; so, I created one for this reason as follows:

{ 
    "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" 
        } 
    ] 
}

Now, I just need to put it on my ListView. I've created a class (JSONParser) as follows:

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

So, I'm stuck in where I'm trying to put my JSON data (in JSONParser class) and I don't know what I should do.

What I've tried so far is written in the following:

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

On the url, I didn't put anything since I don't have an URL, I've got an assets folder with the JSON but I don't know if it will work...

I created an instance from JSONParser class and I get the JSON strings of URL. Also, I created a loop through all items for storing each JSON item in the variable.

Now, I'm stuck and can't find a way to put this data inside my ListView. Also since I can't make a test... :(

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

My ListView with an example without JSON data as follows:

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

Thanks in advance.

EDIT

I have already a ListViewItem and you can see its related code lines in below:

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

And the code lines for ListViewDemoAdapter are as follows:

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

EDIT2

Now, what I'm trying to do is :

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

}

Where I still have the data placed by myself (thing that I don't want), on the url I have put an html created by me (I don't know if it works) and I've implemented a HashMap, but I'm not done at all.

Upvotes: 1

Views: 2578

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

you are almost there. you need a class that represent the information and it is usually part of the model. Let's call this class Product,

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

then declare an ArrayList<Product>, and at every iteration of your loop, create an instance of Product, fill it up, and add it to the 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();
}

Upvotes: 3

Related Questions