I have a ListView with some items, but after I update a Database I'd like to "refresh" the ListView. Anyone can help me?
EDIT: populateListView add items to ListView
public void populateListView()
{
String URL = config.getUrl_For_Query() + ",&nameq=Select&tipo=select"; // my URL
String jsonString = reading.execute_query(URL); // jsonString is formatted well
try
{
JSONObject jsonResponse = new JSONObject(jsonString);
JSONArray array = jsonResponse.getJSONArray("elenco");
for (int i=0; i<array.length(); i++) // I scan all array
{
JSONObject nameObj = (JSONObject)array.get(i);
// I retrieve all information
allNames.add(nameObj.getString("name")); // Name
allLng.add(nameObj.getString("lng")); // Another information
}
}
catch (Exception e)
{ e.printStackTrace(); }
List<String> Array = new ArrayList<String>();
for(int i=0;i<allNames.size();i++) // I add all values
{
String value = allNames.get(i).toString() + ", \n\t" + allLng.get(i).toString();
Array.add(value); // here I populate my Array
}
final ListView listView = (ListView) getActivity().findViewById(R.id.List);
listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array));
//
// Click
//
}
saveChanges
public void saveChanges()
{
// I update a Database
// And then I'd like to refresh ListView's items
populateListView(); // Update ListView
}
Use a Comparator. There you define what to compare and how, in the compare() method you define what should be returned from two of your instances. Here's an example for a String Comparator.
Comparator myComparator = new Comparator<String>() {
public int compare(final String user1, final String user2) {
// This would return the ASCII representation of the first character of each string
return (int) user2.charAt(0) - (int) user1.charAt(0);
};
};
adapter.sort(myComparator);
This way, when you add an item, you don't have to recreate the whole Adapter but it will be sorted instead. But don't forget to call .notifyDataSetChanged() on your adapter, this will make (amongs other things) to refresh your layout.
Try using ArrayAdapter.insert method to insert objects in specific index.
At first take a look at this tutorial about SQlite database in Android.
So, your problem is that new items are added at the end of the list. Huh? This is because you have not notified Adapter from the changes of the Array.
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array);
Your first solution is to clear Adapter before updating Database. Sth like:
Adapter.clear(); can do that. This way your Adapter is empty before updating database and new items are inserted. You can use Adapter.notifyDataSetChanched(); for awaring Adapter about the changes.
In above tutorial there is a custom Adapter. It uses this code:
List<String> Array = new ArrayList<String>();
Array = (ArrayList<String>) db.getAllContacts();
Adapter = new MyCustomAdapter(getActivity() [in fragment case or getApplicationContext() in Activity case], R.layout.simple_list_item_1, Array);
This way there is no need for clearing Adapter because it automatically does that. Wherever you use this method, updated adapter is used for showing the list.
Related
String sessionId = getIntent().getStringExtra("numbers");
final String[] values = new String[]{sessionId};
ArrayList list = new ArrayList<>(Arrays.asList(values));
final ArrayList arrayList = new ArrayList();
for (int i = 0; i < values.length; i++)
{
Log.d(TAG, "listValue -" + values[i]);
arrayList.add(values[i]);
}
listView = (ListView)findViewById(R.id.textView2);
listView.setAdapter(new
ArrayAdapter(ListDisplayActivity.this,R.layout.list_display,R.id.text, arrayList));
How to fix listview value single string have multiple values for android?
You can pass values like
intent.putStringArrayListExtra("sessionIds",yourSessionIdList);
and get like
ArrayList<String> sessionIds = getIntent().getStringArrayListExtra("sessionIds");
Check the below link: You may need to use custom adapter to display multiple values in each row of listview:
Listview with custom adapter
And I also recommend you to use recyclerview instead of listview
hi can you help me how to display the next 10 data in json by click the next button. i have 50 data and i want to display first 10. Then when I click the next button, 11-20 will display in listview. Ill post my code below and i dont have any idea how to do it. Also when i click previous button it will go back to previous listview which is 1-10. Thanks!
doctordata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(d);
jsonArray = jsonObject.optJSONArray("Doctors");
int arraylength = jsonArray.length();
for (int i = 0; i < arraylength; i++) {
Map<String, String> doctormap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
doctor = jsonChildNode.optString("Name").toString();
specialty = jsonChildNode.optString("Specialty").toString();
doctormap.put("name", doctor);
doctormap.put("specialty", specialty);
doctordata.add(doctormap);
}
String[] from = {"name", "specialty"};
int[] views = {R.id.doctorlist_name, R.id.doctorlist_specialty,};
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, doctordata, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();
}
Define a class called Doctors, with fields String name and String Specialty, and add the Doctors to a list that you can iterate or convert to Array.
class Doctors {
private final String specialty;
private final String name;
public Doctors (){
specialty= "Spe1";
name = "name";
}
}
public String convertToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
Ok, there are several ways to do what do you want to achieve. I will explain you how I would do it:
Firts, in the doctorData arraylist you have all the items (50 items) that you need to show.
Create a partialDoctorData arraylist and assing to it only the first 10 items from doctorData, ok? and add this new arraylist to the SimpleAdaper.
So you will need to do instead of your code:
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, **partialDoctorData**, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
So when the user click in the next button, you can clean the partialDoctorData content, add from the 11-20 items from the original doctorData arrayList and and and directly call to the
myadapter.notifyDataSetChanged();
(you don't have to repeat the step to create a new SimpleAdapter, only changing the values of the arraylist and calling to this method, the content of the list is going to be updated with the content of the partialDoctorData)
Try ;)
Try this one:
Android ListView with Load More Button
You can use pagination when 10 items will be loaded after that you will call agin api to get next 10 items
Trying to make a listview with data from JSON. phonelist decalred below hold the data parsed from the json.
ArrayList<HashMap<String, String>> phonelist = new ArrayList<HashMap<String, String>>();
I am doing this in onCreateView of the fragment
for (int i = 0; i < phone.length(); i++) {
try {
JSONObject c = phone.getJSONObject(i);
String phId = c.getString("ph_id");
String phNo = c.getString("ph_no");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ph_id", phId);
map.put("ph_no", phNo);
phonelist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
ListView list = (ListView) rootView.findViewById(R.id.listview1);
ListAdapter adapter = new SimpleAdapter(getActivity(), phonelist,
R.layout.list_item_phone,
new String[]{"ph_id", "ph_no"}, new int[]{
R.id.txtPhoneID, R.id.txtPhoneNum});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO
}
});
The phonelist is getting populated from json and here is its content
[{ph_id=1, ph_no=0120-2550000}, {ph_id=2, ph_no=1860-180-3474}, {ph_id=3, ph_no=0120-4698114}, {ph_id=4, ph_no=0361-2525256}, {ph_id=5, ph_no=033-2525368}, {ph_id=6, ph_no=011-25252525}, {ph_id=7, ph_no=0361-2525257}, {ph_id=8, ph_no=033-2525369}, {ph_id=9, ph_no=011-25252526}, {ph_id=10, ph_no=0361-2525258}, {ph_id=11, ph_no=033-2525370}, {ph_id=12, ph_no=011-25252527}]
For some reason though, only the first item shows up in the listview.
Edit:
Declaration of the phone variable
JSONArray phone = null;
And then I am getting its value onCreate like below
phone = ((JSonArrayParser) getArguments().getParcelable("phoneJsonArray")).getJsonArray();
phone.length is showing correct value (12)
HashMap is specified as key and value, based on webpage # Map. Search text for "put (K key, V value)" for reference. In your code:
map.put("ph_id", phId);
map.put("ph_no", phNo);
I can see only 2 keys are added into this map object, even though you added lots of data from JSON.
As a suggestion, instead of literal string "ph_id" as the key, you can have variable phId as key instead, and the value can be phNo. That can be one code design.
Maybe it's a good idea if you post the SimpleAdapter also, especially in getView().
I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)
I am having a problem updating a TextView in real time. I want to update the TextView of a ListView with a custom adapter in real time. I have my socket I/O handler on which I receive a JSON message. I want to parse this JSON and put that text into the particular list row with setText(). How do I get the index of that ListView row and update its TextView?
responseid=object.getString("ResponseID");
if(responseid!=null){
for(int j=0;j<countryList.size();j++){
//If the countryList row match then i want to update the textView of that particular row
if(countryList.get(j).getName().equals(caseid)) {
int oldcount = Integer.parseInt((dataAdapter.findViewById(R.id.replycount)).getText().toString());
int total=oldcount+1;
(dataAdapter.findViewById(R.id.replycount)).setText(Integer.toString(total));
dataAdapter.notifyDataSetChanged();
}
}
}
Here is my solution:
for(int j=0;j<countryList.size();j++)
{
if(countryList.get(j).getName().equals(caseid))
{
String oldcount = countryList.get(j).getCount();
int oldcountint = Integer.parseInt(oldcount);
int newcount = oldcountint + 1;
countryList.get(j).setCount(Integer.toString(newcount));
dataAdapter.notifyDataSetChanged();
break;
}
}
You should alter the items in your ListAdapter, and then call notifyDataSetChanged().
Example:
//Creating and adding ListAdapter to ListView
MyObject myFirstObject = new MyObject("Test1");
MyObject mySecondObject = new MyObject("Test2");
MyAdapter myAdapter = new MyAdapter();
myAdapter.add(myFirstObject);
myAdapter.add(mySecondObject);
myListView.setAdapter(myAdapter);
When updating a particular position:
myAdapter.getItem(position).text = "My updated text";
myAdapter.notifyDataSetChanged();