Use ArrayAdapter with ArrayList - android

I'm currently building an Android Agenda Activity which consists in 4 ListView. Basicaly, I got the method onAgendaDataReady(ArrayList appointments) that is called by a WebServiceCoordinator. This method sorts the appointments and that way, populates 4 new ArrayList. The code is the following :
#Override
public void onAgendaDataReady(ArrayList<Appointment> appointments) {
//swipeContainer.setRefreshing(false);
alert.hide();
ArrayList<Appointment> appointmentsfuturs = new ArrayList<>();
ArrayList<Appointment> appointmentspasses = new ArrayList<>();
ArrayList<Appointment> appointmentsannules = new ArrayList<>();
ArrayList<Appointment> appointmentsaconfimer = new ArrayList<>();
for (Appointment a : appointments) {
if (a.stateId == 2)
appointmentsaconfimer.add(a);
else if (a.stateId == 6)
appointmentsannules.add(a);
else if (a.stateId == 5)
appointmentspasses.add(a);
else if (a.stateId == 4)
appointmentsfuturs.add(a);
}
ArrayAdapter<Appointment> adapterfuturs = new ArrayAdapter<>(AgendaActivity.this, android.R.layout.simple_list_item_1, appointmentsfuturs);
ArrayAdapter<Appointment> adapterpasses = new ArrayAdapter<>(AgendaActivity.this, android.R.layout.simple_list_item_1, appointmentspasses);
ArrayAdapter<Appointment> adapterannules = new ArrayAdapter<>(AgendaActivity.this, android.R.layout.simple_list_item_1, appointmentsannules);
ArrayAdapter<Appointment> adapteraconfirmer = new ArrayAdapter<>(AgendaActivity.this, android.R.layout.simple_list_item_1, appointmentsaconfimer);
rdvFutursListView.setAdapter(adapterfuturs);
rdvPassesListView.setAdapter(adapterpasses);
rdvAnnulesListView.setAdapter(adapterannules);
rdvAConfirmerListView.setAdapter(adapteraconfirmer);
adapterfuturs.notifyDataSetChanged();
adapterpasses.notifyDataSetChanged();
adapterannules.notifyDataSetChanged();
adapteraconfirmer.notifyDataSetChanged();
}
This code is working, but I don't want anymore to use the android.R.layout.simple_list_item_1 layout. So I built an ArrayAdapter with a custom layout.
My problem / question is the following : how to pass the ArrayList created by onAgendaDataReady() to my Adapter ?
I tried to do this :
appointmentItemAdapter = new AppointmentItemAdapter(this);
rdvFutursListView.setAdapter(appointmentItemAdapter);
appointmentItemAdapter.add(adapterfuturs);
But the appointmentItemAdapter requires an Appointment and not an ArrayList.
Thanks for your help
--------------- FINAL SOLUTION -----------------
AppointmentItemAdapter appointmentFutursItemAdapter = new AppointmentItemAdapter(AgendaActivity.this);
rdvFutursListView.setAdapter(appointmentFutursItemAdapter);
appointmentFutursItemAdapter.addAll(appointmentsfuturs);
appointmentFutursItemAdapter.notifyDataSetChanged();

I think you are mixing different things here.
Your custom Adapter has to take an ArrayList (or any Collection) as input parameter and return the current items to the list (based on the position queried)
So it is not sufficient to pass a single Appointment as parameter.

Related

Android add items to Listview.setAdapter which contains only specific items

Is there any possible way to add items in listview using setAdapter which only contains specific items? for example I want to add in listview an items which contains a date of "Feb. 15, 2015" only.
Following the codes:
final 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);
SimpleDateFormat formatdate = new SimpleDateFormat("MMM. dd, yyyy");
String selecdate = formatdate.format(date);
if (eventDates.contains(selecdate)) {
myList.setAdapter(adapter); //these line I want only to add items in listview which contains the value of 'selectdate'
}
else {
myList.setAdapter(null);
}
SimpleAdapter is used for static data. Since you want to dynamically filter the data you should implement a custom adapter to do this. However, a cheap solution would be to filter the data before you setup the adapter. Like this:
ListView myList = (ListView) findViewById(android.R.id.list);
SimpleDateFormat formatdate = new SimpleDateFormat("MMM. dd, yyyy");
String selecdate = formatdate.format(date);
// Filter selected events
List<Map<String, Object>> filteredEventsList = new ArrayList<Map<String, Object>>();
for (Map<STring, Object> row : eventsList) {
if (row should be shown) {
filteredEventsList.add(row);
}
}
final ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, filteredEventsList, 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});
myList.setAdapter(adapter);

How to select one value of a JSON to display on ListView using ArrayAdapter

Currently my ListView is displaying the following:
Object[id=1, name=Object 1, ...]
Object[id=2, name=Object 2, ...]
Object[id=3, name=Object 3, ...]
List<Object> listObject = getObjectListFromJson(jSonObjects);
ArrayAdapter<Object> objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listObject);
I want to display only the "name" value of the JSON like:
Object 1
Object 2
Object 3
Do I need to write a custom adapter or is there a way to get "name" variable using the default one?
Sorry, I'm a beginner on Android development and to stackoverflow. Ask me if you need more information.
After
List<Object> listObject = getObjectListFromJson(jSonObjects);
do
List<String> nameList = new ArrayList<String>();
for (int i=0; i<listObject.size(); i++) {
nameList.add(listObject.get(i).name); // Change ".name" to the appropriate way to get the name of the object. It depends on the object
}
and change
ArrayAdapter<Object> objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listObject);
to
ArrayAdapter<String> objectArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, nameList);
If you have getObjectListFromJson create some custom object type to hold the ID and the name, then all you need to do is add a toString method on that class to return the name portion. For example:
class MyObject {
long id;
String name;
public String toString() { return name; }
}
List<MyObject> listObject = getObjectListFromJson(jSonObjects);
ArrayAdapter<MyObject> objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listObject);

ListView refresh items

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.

BaseAdapter not getting refreshed after data set is changed: Android

I am using a list adapter and feeding a list to it, which is made from a TreeMap.
Treemap is required as I need that the data for the list comes from three places and I need to collect it all and then have it sorted basing on a time stamp.
Now, when the new data comes in, the adapter doesn't update, even when I call notifyDataSetChanged().
I have attached my code below:
LinkedList<DeviceDataInfo> tsDataList = response
.getDeviceDataInfoList();
for (DeviceDataInfo data : tsDataList) {
// if (data.getAttrValue().equals("14")){
String eventMsg = null;
if (data.getAttrValue() != null) {
eventMsg = getEventMessage(
Float.valueOf(data.getAttrValue()),
data.getAttrName());
if (eventMsg != null) {
long time = data.getTime();
String eventDate = mCurrentDoorSensor
.getFormattedDate(time);
String eventTime = mCurrentDoorSensor
.getFormattedTime(time);
SensorListModel item = new SensorListModel(eventTime,
eventDate, eventMsg);
if (!mDoorSensorHistory.containsKey(time)) {
// add item to the tree
mDoorSensorHistory.put(time, item);
}
}
}
}
SensorListModel[] list = new SensorListModel[mDoorSensorHistory
.size()];
list = mDoorSensorHistory.values().toArray(list);
mList = new ArrayList<SensorListModel>(Arrays.asList(list));
mSensorProgressBar.setVisibility(View.GONE);
mSensorProgressBarText.setVisibility(View.GONE);
if (isAdded()) {
if (mSensorAdaptor == null) {
mSensorAdaptor = new SensorListAdaptor(getActivity(),
mList, "DOOR");
mSensorList.setAdapter(mSensorAdaptor);
} else {
// mSensorAdaptor = new SensorListAdaptor(getActivity(),
// mList, "DOOR");
((BaseAdapter) mSensorList.getAdapter())
.notifyDataSetChanged();
}
}
Could someone, please, let me know what is going wrong?
Thanks
For future reference: This solved it
#Sunny : try mSensorAdaptor.addAll(list);mSensorAdaptor.notifyDataSetChanged(); if addAll method is not available then you will need to define addAll method in SensorListAdaptor which all two ArrayLists – ρяσѕρєя K 15 mins ago

Combine 2 ArrayAdapter

i want to make a Real Time Trading App.. but i have a problem to combine 2 adapter into one adapter. so i need help from you all :D
here's my code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
final uraikonversiActivity cp = new uraikonversiActivity(this);
final ListView list = (ListView) findViewById (R.id.list);
final String list_array[] = new String[cp.kodekonversi.size()];
final Float list_nilai[] = new Float[cp.nilaikonversi.size()];
for (int i = 0; i < cp.kodekonversi.size(); i++) {
list_array[i] = cp.kodekonversi.get(i);
}
for (int i = 0; i < cp.nilaikonversi.size(); i++) {
list_nilai[i] = cp.nilaikonversi.get(i);
}
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_array);
ArrayAdapter adapter1 = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list_nilai);
list.setAdapter(adapter);
}}
(note : this a real time so i got the arraylist from the internet)
my goal is to show something like this at the list = "USD - 1.xxxxx".
thanks in advance :)
At last you are displaying all data withing one listview.So just convert both arrays into one like this(as both arrays are of same lenth):
String[] finalArray = new String[list_array.length + list_nilai.length];
for(int i = 0; i< cp.nilaikonversi.size(); ++i)
finalArray[i] = list_array[i] +"-" + list_nilai[i];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, finalArray);
list.setAdapter(adapter);
Hope it will help you. :)
Build up your own adapter, do not just rely on ArrayAdapter.
When building an adapter there is the method public View getView(int position, View convertView, ViewGroup parent) in wich you can code how every single line should look like. Just return a layout containing two textfields wich are filled by your list_array and list_nilai.
See also: http://developer.android.com/reference/android/widget/Adapter.html
or for a complete tutorial: http://developerlife.com/tutorials/?p=327

Categories

Resources