Faced such a problem in your application:
There is a JSON file located on a remote server, in its application added a class inherited from AsyncTask , which parses the data from JSON and displays the data on the device screen using ListView . In the onCreate method of the onCreate class, MainActivity create an object of the class previously written, thereby performing the task (parse the JSON data and display it on the screen).
Also added a button to update the information. In the event handler for this button, I clear the setAdapter my ListView and create a new class object that parses the data. It was assumed that there would be just an update of the information in the list, but it turned out that the newly updated data are written simply at the end of the list.
Tell me, how can I update the necessary information?
Adapter code to add entries to the ListView:
ListAdapter adapter = new SimpleAdapter( MainActivity.this, itemsList, R.layout.list_item, new String[]{ "currentPrice", "basePrice", "route", "bidsCount"}, new int[]{R.id.currentPrice, R.id.basePrice, R.id.route, R.id.bidsCount} ); listView.setAdapter(adapter); Event handler for Refresh button:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listView.setAdapter(null); new GetInfo().execute(); } }); Part of the GetInfo class, namely the doInBackground(Void... arg0) method doInBackground(Void... arg0) , where parsing and adding data to the HashMap takes place:
for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); JSONObject data = item.getJSONObject("data"); JSONObject bid = item.getJSONObject("bid"); JSONObject bidData = bid.getJSONObject("data"); String currentPrice = bidData.getString("currentPrice"); String basePrice = bidData.getString("basePrice"); String bidsCount = data.getString("bidsCount"); String route = data.getString("route"); HashMap<String, String> itemHashMap = new HashMap<>(); itemHashMap.put("currentPrice", getString(R.string.current_price) + " " + currentPrice); itemHashMap.put("basePrice", getString(R.string.base_price) + " " + basePrice); itemHashMap.put("route", getString(R.string.route) + " " + route); itemHashMap.put("bidsCount", getString(R.string.bids_count) + " " + bidsCount); itemsList.add(itemHashMap); }
ListView. - post_zeew Nov.GetInfocode. - post_zeew Nov.itemsListis an object of what class? - post_zeew