BaseAdapter not getting refreshed after data set is changed: Android - 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

Related

Use ArrayAdapter with ArrayList

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.

How to select multiple Checkbox and create an Array with the values in android

I have added 9 CheckBox in my Fragment which is getting checked
according to the response from JSON. If user wants to update his/her
profile, He/she can check/uncheck any of them. Now I have to confirm
that how many of them are checked and create an Array as a
parameter according to that. I am not using any adapter for that.
please let know how to set the condition to get the value of only
checked checkboxes
I am trying to do like this
cb_prfl_setng_general=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_general);
cb_prfl_setng_economics = (CheckBox)rootView.findViewById(R.id.cb_prfl_setng_economics);
cb_prfl_setng_business=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_business);
cb_prfl_setng_social=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_social);
cb_prfl_setng_politics=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_politics);
cb_prfl_setng_entertainmnt=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_entertainmnt);
cb_prfl_setng_technology=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_technology);
cb_prfl_setng_spritual=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_spritual);
cb_prfl_setng_sports=(CheckBox)rootView.findViewById(R.id.cb_prfl_setng_sports);
if(cb_prfl_setng_general.isChecked()){
String[] Interest = {"catagory_id=1"};
}else if(cb_prfl_setng_economics.isChecked()){
String[] Interest = {"catagory_id=1","catagory_id=2"};
}else if(cb_prfl_setng_general.isChecked()){
String[] Interest = {"catagory_id=1","catagory_id=2","catagory_id=3"};
}else if(cb_prfl_setng_entertainmnt.isChecked()){
String[] Interest = {"catagory_id=1","catagory_id=2","catagory_id=3","catagory_id=4"};
}
But I don't think this is the right way to get the exact value.
You need to test each checkbox separately and accumulate the category ids:
List<String> interestList = new ArrayList<String>();
// for each checkbox checked, accumulate a category id in the list
if (cb_prfl_setng_general.isChecked()) {
interestList.add("catagory_id=1");
}
if (cb_prfl_setng_economics.isChecked()) {
interestList.add("catagory_id=2");
}
if (cb_prfl_setng_general.isChecked()) {
interestList.add("catagory_id=3");
}
if (cb_prfl_setng_entertainmnt.isChecked()) {
interestList.add("catagory_id=4");
}
.
.
.
// convert the list into an array
String[] interest = interestList.toArray(new String[interestList.size()]);
System.out.println("interest");
for (String str : interest) {
System.out.println(str);
}
String WeekDays="";
List DayList = new ArrayList();
if (cbSunday.isChecked()) {
DayList.add(String.valueOf(cbSunday.getText()));
}
if (cbMonday.isChecked()) {
DayList.add(String.valueOf(cbMonday.getText()));
}
if (cbTuesday.isChecked()) {
DayList.add(String.valueOf(cbTuesday.getText()));
}
if (cbWednesday.isChecked()) {
DayList.add(String.valueOf(cbWednesday.getText()));
}
if (cbThursday.isChecked()) {
DayList.add(String.valueOf(cbThursday.getText()));
}
if (cbFriday.isChecked()) {
DayList.add(String.valueOf(cbFriday.getText()));
}
if (cbSaturday.isChecked()) {
DayList.add(String.valueOf(cbSaturday.getText()));
}
String[] Days = DayList.toArray(new String[DayList.size()]);
WeekDays="";
for (String str : Days) {
if(WeekDays.equals(""))
{
WeekDays=WeekDays+str;
}
else {
WeekDays = WeekDays + "," + str;
}
WeekDays=WeekDays;
Log.d("LogDays",WeekDays);
}

How to remove duplicates from ArrayList of type Object? [duplicate]

This question already has answers here:
How to remove duplicates from a list?
(15 answers)
Closed 8 years ago.
I want to remove duplicates from ArrayList of type Alerts where Alerts is a class.
Class Alerts -
public class Alerts implements Parcelable {
String date = null;
String alertType = null;
String discription = null;
public Alerts() {
}
public Alerts(String date, String alertType, String discription) {
super();
this.date = date;
this.alertType = alertType;
this.discription = discription;
}
}
Here is how I added the elements -
ArrayList<Alerts> alert = new ArrayList<Alerts>();
Alerts obAlerts = new Alerts();
obAlerts = new Alerts();
obAlerts.date = Date1.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
obAlerts = new Alerts();
obAlerts.date = Date2.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
What I want to remove from them-
I want all alerts which have unique obAlerts.date and obAlerts.alertType. In other words, remove duplicate obAlerts.date and obAlerts.alertType alerts.
I tried this -
Alerts temp1, temp2;
String macTemp1, macTemp2, macDate1, macDate2;
for(int i=0;i<alert.size();i++)
{
temp1 = alert.get(i);
macTemp1=temp1.alertType.trim();
macDate1 = temp1.date.trim();
for(int j=i+1;j<alert.size();j++)
{
temp2 = alert.get(j);
macTemp2=temp2.alertType.trim();
macDate2 = temp2.date.trim();
if (macTemp2.equals(macTemp1) && macDate1.equals(macDate2))
{
alert.remove(temp2);
}
}
}
I also tried-
HashSet<Alerts> hs = new HashSet<Alerts>();
hs.addAll(obAlerts);
obAlerts.clear();
obAlerts.addAll(hs);
You need to specify yourself how the class decides equality by overriding a pair of methods:
public class Alert {
String date;
String alertType;
#Override
public boolean equals(Object o) {
if (this == 0) {
return true;
}
if ((o == null) || (!(o instanceof Alert)))
return false;
}
Alert alert = (Alert) o;
return this.date.equals(alert.date)
&& this.alertType.equals(alert.alertType);
}
#Override
public int hashCode() {
int dateHash;
int typeHash;
if (date == null) {
dateHash = super.hashCode();
} else {
dateHash = this.date.hashCode();
}
if (alertType == null) {
typeHash = super.hashCode();
} else {
typeHash = this.alertType.hashCode();
}
return dateHash + typeHash;
}
}
You can then loop through your ArrayList and add elements if they aren't already there as Collections.contains() makes use of these methods.
public List<Alert> getUniqueList(List<Alert> alertList) {
List<Alert> uniqueAlerts = new ArrayList<Alert>();
for (Alert alert : alertList) {
if (!uniqueAlerts.contains(alert)) {
uniqueAlerts.add(alert);
}
}
return uniqueAlerts;
}
However, after saying all that, you may want to revisit your design to use a Set or one of its family that doesn't allow duplicate elements. Depends on your project. Here's a comparison of Collections types
You could use a Set<>. By nature, Sets do no include duplicates. You just need to make sure that you have a proper hashCode() and equals() methods.
In your Alerts class, override the hashCode and equals methods to be dependent on the values of the fields you want to be primary keys. Afterwards, you can use a HashSet to store already seen instances while iterating over the ArrayList. When you find an instance which is not in the HashSet, add it to the HashSet, else remove it from the ArrayList. To make your life easier, you could switch to a HashSet altogether and be done with duplicates per se.
Beware that for overriding hashCode and equals, some constraints apply.
This thread has some helpful pointers on how to write good hashCode functions. An important lesson is that simply adding together all dependent fields' hashcodes is not sufficient because then swapping values between fields will lead to identical hashCodes which might not be desirable (compare swapping first name and last name). Instead, some sort of shifting-operation is usually done before adding the next atomic hash, eg. multiplying with a prime.
First store your datas in array then split at as one by one string,, till the length of that data execute arry and compare with acyual data by if condition and retun it,,
HashSet<String> hs = new HashSet<String>();
for(int i=0;i<alert.size();i++)
{
hs.add(alert.get(i).date + ","+ alert.get(i).alertType;
}
alert.clear();
String alertAll[] = null;
for (String s : hs) {
alertAll = s.split(",");
obAlerts = new Alerts();
obAlerts.date = alertAll[0];
obAlerts.alertType = alertAll[1];
alert.add(obAlerts);
}

Why does my SparseArray return an ArrayList with zero elements?

I'm iterating through a cursor and populating a SparseArray with ArrayList's containing bundles of information from the cursor:
// An ArrayList to hold all of our components per section
ArrayList<ObjectKanjiLookupChar> al = new ArrayList<ObjectKanjiLookupChar>();
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();
do
{
// Read values from the cursor
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String component = cursor.getString(cursor.getColumnIndex("component"));
int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));
// Create a new object for this component so we can display it in the GridView via an adapter
ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
oklc.setCharacterID(id);
oklc.setCharacter(component);
oklc.setStrokeCount(compStrokes);
al.add(oklc);
// Add headers whenever we change stroke groups
if(compStrokes != strokesSection)
{
compArray.put(strokesSection, al);
al.clear();
strokesSection = compStrokes;
}
}
while(cursor.moveToNext());
// Add the final group of components to the array
compArray.put(strokesSection, al);
Immediately afterwards, I iterate through the SparseArray:
for(int i = 0; i < compArray.size(); i++)
{
Integer strokes = compArray.keyAt(i);
ArrayList<ObjectKanjiLookupChar> alComp = compArray.get(strokes);
// DEBUG
Log.i("DialogKanjiLookup", "Components in Section " + strokes + ": " + alComp.size());
ll.addView(createNewSection(String.valueOf(strokes), alComp));
}
For some unknown reason, the Log() call above reports that alComp has zero entries. I verified that ArrayList.size() was returning numbers greater than 0 when I put() them into the SparseArray, so I must be doing something incorrect when iterating through the SparseArray. What is going on?
I suspect that the problem comes from this piece of code:
if(compStrokes != strokesSection)
{
compArray.put(strokesSection, al);
al.clear(); // Here
strokesSection = compStrokes;
}
You cleared the array list after you added to the SparseArray. You might think that after you have added the list to the SparseArray, SparseArray would keep a copy of the ArrayList. However, they actually share the same reference. Since you cleared the ArrayList, you cleared out the one inside SparseArray too.
The following code should fix the problem.
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();
do
{
// Read values from the cursor
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String component = cursor.getString(cursor.getColumnIndex("component"));
int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));
// Create a new object for this component so we can display it in the GridView via an adapter
ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
oklc.setCharacterID(id);
oklc.setCharacter(component);
oklc.setStrokeCount(compStrokes);
ArrayList<ObjectKanjiLookupChar> al = compArray.get(comStrokes);
if(al == null) {
al = new ArrayList<ObjectKanjiLookupChar>();
compArray.put(comStrokes, al);
}
al.add(oklc);
}
while(cursor.moveToNext());

NullPointerException while using adapter.getItem(position)

I have the following code in WeekDays.java
ArrayAdapter<TaskInAWeek> adapter1 = (ArrayAdapter<TaskInAWeek>) getListAdapter() ;
TaskInAWeek taski;
ArrayList<Long> checkedItms = new ArrayList<Long>();
ArrayList<Long> uncheckedItms = new ArrayList<Long>();
for(int i=0;i<values.size();i++)
{
Log.i("value's size:" +values.size()," ");
if(EditStatusAdapter.tog==1)
{
Log.i("i::"+i," ");
taski = adapter1.getItem(i);
long id = taski.getId();
Log.i("nid:"+id," ");
checkedItms.add(id);
}
else
{
Log.i("i::"+i," ");
taski = adapter1.getItem(i);
long id = taski.getId();
Log.i("nid:"+id," ");
uncheckedItms.add(id);
}
}
Its custom Array Adapter is EditStatusAdapter.java. I get a NullPointerException at this pttaski = adapter1.getItem(i);.
I have used similar one in one of my activity but it did work fine. I guess its due to the custom array adapter. But I could not ignore it as well. Can anyone tel me how to clear the exception?

Categories

Resources