Update ListView without data beiing changed - android

In my app I have a ListView that contains times of different timezones. With a seekbarthe user can change the current time of a timezone and the other zones are supposed to update their times as well.
In my onCreate() method I iniciate the ListView and set a Time variable to the current time of my previously selected location. In addition I set aOnSeekBarChangeListener to my seekbar.
private ArrayList<Welt> welts;
private SimpleArrayAdapter arrayAdapter;
public void onCreate(Bundle savedInstanceState) {
...
arrayAdapter = new SimpleArrayAdapter(this, R.layout.listwelt, welts);
showwelt();
...
now.setToNow();
now.set(now.toMillis(false));
pos = extras.getInt("weltcompare");
now.switchTimezone(welts.get(pos).zone);
...
seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
offset = seekBar.getProgress()*5 - start;
arrayAdapter.notifyDataSetChanged();
//showwelt();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
offset = seekBar.getProgress()*5 - start;
arrayAdapter.notifyDataSetChanged();
//showwelt();
}
});
...
}
public void showwelt() {
ListView listTest = (ListView)findViewById(R.id.mylistwelt);
listTest.setAdapter(arrayAdapter);
listTest.setDivider(null);
listTest.setDividerHeight(0);
}
At last my ArrayAdapter class:
public class SimpleArrayAdapter extends ArrayAdapter<Welt> {
private final int resource;
public SimpleArrayAdapter(Context context, int resource, ArrayList<Welt> arrays) {
super(context, resource, arrays);
this.resource = resource;
}
public View getView(int position, View convertView, ViewGroup parent) {
Welt cobject = getItem(position);
RelativeLayout listView;
if(convertView==null) {
listView = new RelativeLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, listView, true);
}else{
listView = (RelativeLayout) convertView;
}
TextView tv1 = (TextView)listView.findViewById(R.id.listwelt1);
tv1.setText(cobject.ort);
TextView tv2 = (TextView)listView.findViewById(R.id.listwelt2);
tv2.setText(cobject.land);
TextView tv3 = (TextView)listView.findViewById(R.id.listwelt3);
now.set(base);
now.minute = now.minute + offset;
now.normalize(false);
now.set(now.toMillis(false));
now.switchTimezone(cobject.zone);
tv3.setText(TimeMateActivity.formatDateTime(0, 0, 0, now.hour, now.minute));
TextView tv4 = (TextView)listView.findViewById(R.id.listwelt4);
tv4.setText(TimeMateActivity.formatDateTime(now.monthDay, now.month, now.year, 24, 0));
if(position == pos) {
tv1.setTypeface(null, Typeface.BOLD);
tv2.setTypeface(null, Typeface.BOLD);
tv3.setTypeface(null, Typeface.BOLD);
}
return listView;
}
}
So the only data that is changed while the activity is running is the variable offset.
I think that's the reason why arrayAdapter.notifyDataSetChanged() doesn't work, while calling showwelt() in the OnSeekBarChangeListener does the job, but resets the ListView to the top.
I read a couple of posts, but none of them helped.
I tried to clear the adapter and add all items again before calling notifyDataSetChanged().
I tried saving the current scroll position of the list and restore it.
How should I solve my problem?

It looks to me like you are using "now" in your adapter, so you're never to to be able to change it. You need to find a way to get the seekbar value into the adapter and use that instead of "now". then use .invalidate() to force a redraw of the list .

I found a solution:
My OnSeekBarChangeListener methods now look like this.
OnProgressChanged: here I calculate the value for my offset variable and call the showwelt() function
OnStartTrackingTouch: here I save the current scroll position of the listview
OnStopTrackingTouch: empty
And my showwelt function looks like this:
public void showwelt() {
ListView listTest = (ListView)findViewById(R.id.mylistwelt);
SimpleArrayAdapter arrayAdapter = new SimpleArrayAdapter(this, R.layout.listwelt, welts);
listTest.setAdapter(arrayAdapter);
listTest.setDivider(null);
listTest.setDividerHeight(0);
listTest.setSelectionFromTop(index, top);
}

Related

Assign listener at onCreate time to subviews of dynamic loaded ListView items

I have a ListView managed by an ArrayList/ArrayAdapter.
The ListView item is defined in an XML layout file.
At initialisation time (onCreate) I load the ListView with a variable number of items and, at that moment, I need to assign a listener to one subview (a SeekBar) of each item.
This is the relevant part of the code:
private String TAG = "MainActivity";
private ListView lv_controlli;
private ArrayAdapter<String> adapter;
private LinkedHashMap<String, String> hmControlli;
private ArrayList<String> controlli;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
private void Init() {
lv_controlli = (ListView) findViewById(R.id.LV_Controls);
hmControlli = new LinkedHashMap<String, String>();
for (int i = 0; i < 6; i++) hmControlli.put(String.valueOf(i), "Gruppo " + i);
controlli = new ArrayList<String>(hmControlli.keySet());
adapter = new ArrayAdapter<String>(this, R.layout.control_layout, R.id.LBL_Controllo, controlli);
lv_controlli.setAdapter(adapter);
for (int i = 0; i < lv_controlli.getChildCount(); i++) {
SeekBar sb = (SeekBar) lv_controlli.getChildAt(i).findViewById(R.id.SB_Intensita);
sb.setOnSeekBarChangeListener(valueOnChange);
}
}
private SeekBar.OnSeekBarChangeListener valueOnChange = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG,String.valueOf(seekBar.getProgress()));
}
...
};
public void click(View view) {
for (int i = 0; i < lv_controlli.getChildCount(); i++) {
SeekBar sb = (SeekBar) lv_controlli.getChildAt(i).findViewById(R.id.SB_Intensita);
sb.setOnSeekBarChangeListener(valueOnChange);
}
}
No listeners are assigned by Init() routine (called by onCreate()) because its execution happens when the ListView has not been already loaded, even though the adapter as been populated and assigned to the ListView.
The same kind of code works perfectly, instead, in the click() routine associated to a button that I press when the control is returned to the user.
So I can get the SeekBars actually usable only after my interaction and this is bad, of course.
Is there any point where the populated ListView is available before the control is returned to the user?
Thanks a lot in advance for your help.
Chances are good that the right way to solve this problem is not by trying to find a moment in time between onCreate() and when control of the app passes to the user, but by assigning your OnSeekBarChangeListener to the SeekBar inside your adapter.
You can create a subclass of ArrayAdapter that you use instead of the base ArrayAdapter implementation, then override getView() to add the listener. Something like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
SeekBar seekBar = (SeekBar) v.findViewById(R.id.SB_Intensita);
seekBar.setOnSeekBarChangeListener(valueOnChange);
return v;
}

A TextView change applies to multiple TextViews using ListView and ArrayAdapter

I've started working on a small project not to long ago, the main goal is to forge a way for me to keep track of my actions during the course of 100 weeks.
I'm still a rookie android developer and I've encountered an issue that I couldn't explain.
Basically I've populated a ListView using the ArrayAdapter with a list containing 100 strings (Week1, Week2, Week3 ... Week100)
Setting up an onclicklistener on each of the TextViews so that when a user performs a click on a textview, the background color would change to red.
However; whenever I click a single textview - more than a single textview is being colored.
Notes:
I'm using a ScrollView to scroll through the entire list. (Once populated, the 100 week list fills up the entire screen, the scroll view is used to access the entire list.)
I also saved a reference to the currently painted textview so I could make sure that when a user clicks a different textview, the previous one would lose its red background.
MainActivity initialization:
public class MainActivity extends ActionBarActivity
{
TextView selectedWeek; // Reference to the selected week.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateWeekList(); // Populating the ListView
initWeekClick(); // Initializing click listener
}
Populating the ListView:
public void populateWeekList()
{
String[] weeks = new String [100]; // 100 weeks
for (int i=0; i<100;i++)
{
weeks[i] = "Week"+(i+1);
}
ArrayAdapter<String> weekAdapter = new ArrayAdapter<String>(
this,
R.layout.weeksview,
weeks
);
// R.id.weekTypeList is just a normal TextView.
ListView weekList=(ListView) findViewById(R.id.weekTypeList);
weekList.setAdapter(weekAdapter);
}
Code for initializing onClickListener and saving the selectedWeek reference:
public void initWeekClick()
{
ListView weekList=(ListView) findViewById(R.id.weekTypeList);
weekList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id)
{
if (selectedWeek != null)
{
selectedWeek.setBackgroundColor(0);
}
TextView clicked = (TextView) viewClicked;
// Change clicked TextView color to red.
clicked.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
// Save the selected week reference
selectedWeek = clicked;
}
});
}
Ok, your background is shuffling because when you scroll your ListView getView() is called and it consider your current position of TextView(as current view) and set background on it as it detect setBackground() method at onClick listener on it..
First I recommend to create a Adapter class extends ArrayAdapter<?>
Solution 1 :
Use setTag() at onClick listener on your text view like..
text.setTag(position);
and above it use getTag() and put condition
if(holder.text.getTag().equals(position)){
holder.text.setBackgroundColor(Color.BLUE);
}else{
holder.text.setBackgroundColor(Color.WHITE);
}
Solution 2 :
Added this to onCreate method
ArrayList<String> _array = new ArrayList<String>();
for(int i=0 ; i <1000; i ++){ // 1000 value
_array.add(i+"");
}
list.setAdapter(new MainAdapter(this, _array)); // pass you list here
ArrayAdapter class :
public class MainAdapter extends ArrayAdapter<String> {
ArrayList<String> _st = new ArrayList<String>();
ArrayList<Integer> check = new ArrayList<Integer>();
Context _context;
public MainAdapter(Context context,ArrayList<String> _st) {
super(context,R.layout.main, _st); // your inflate layout
this._context = context;
this._st = _st;
}
#Override
public int getCount() {
return _st.size();
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//---//
// check if current position is there in arraylist
if(checking(position)){
holder.text.setBackgroundColor(Color.BLUE);
}else{
holder.text.setBackgroundColor(Color.WHITE);
}
holder.text.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// set background and put value in array list
holder.text.setBackgroundColor(Color.BLUE);
check.add(position);
}
});
return convertView;
}
// this will check whether current position is there is array list or not and if it there it will break loop and return true
public boolean checking(int position){
boolean fine = false;
for(int i=0; i<check.size();i++){
if(position == check.get(i)){
fine = true;
break;
}
}
return fine;
}
}
public class ViewHolder{
TextView text;
}
}
I don't how much I am ethical in this code...but as you have specified that you have 100 value.I have tested it on 1000 value and it worked
I am not expert so let me know if I am wrong somewhere
Hope it works !!!

Strikethrough an ArrayList<String> item when long pressed

I'm trying to make a simple to-do list where you would long-press an item to mark it as 'done', in which case it will be greyed out and strikethrough.
I'm working on the strikethrough first and found some sample code here creating a strikethrough text in Android? . However the problem is that the setPaintFlags() method only seems to work on TextView whereas the items on my list are String. I can't cast a String to a TextView, and I found a workaround here but apparently it's highly discouraged to do it: Cast String to TextView . Also I looked up SpannableString but it doesn't seem to work for strings of varying length.
So I'm back at square one - is it at all possible to implement what I'm trying to do? Or will I have to store my list items differently instead?
Relevant code:
public class MainActivity extends ActionBarActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting what the ListView will consist of
lvItems = (ListView) findViewById(R.id.lvItems);
readItems();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
// Set up remove listener method call
setupListViewListener();
}
//Attaches a long click listener to the listview
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Trying to make the onLongClick strikethrough the text
String clickedItem = items.get(pos);
//What do I do here??
// Refresh the adapter
itemsAdapter.notifyDataSetChanged();
writeItems();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
Let's take a step back and consider your app. You want to show a list of jobs to the user. Each job has a description. And each job has two possible states: 'done' or 'not done'.
So I would like to introduce a class 'Job'
class Job
{
private String mDescription;
private boolean mDone;
public Job(String description)
{
this.mDescription = description;
this.mDone = false;
}
// ... generate the usual getters and setters here ;-)
// especially:
public boolean isDone()
{
return mIsDone;
}
}
This way your ArrayList 'items' becomes be a ArrayList< Job >. Wether a job is done or not will be stored together with its description. This is important because you want to show the current state of the job to the user by changing the look of the UI element, but you need to keep track of the job's state on the data level as well.
The UI element - the TextView - will be configured to present information about the job to the user. One piece of information is the description. The TextView will store this as a String. The other piece of information is the state (done/ not done). The TextView will (in your app) store this by setting the strike-through flag and changing its color.
Because for performance reasons a ListView uses less elements than the data list ('items') contains, you have to write a custom adapter. For brevity's sake, I'm keeping the code very simple, but it's worth the time to read up on the View Holder pattern:
Let's use a layout file 'mytextviewlayout.xml' for the list rows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView"/>
</LinearLayout>
Now the code for the adapter looks like this:
EDIT changed from ArrayAdapter to BaseAdapter and added a view holder (see comments):
public class MyAdapter extends BaseAdapter
{
private ArrayList<Job> mDatalist;
private int mLayoutID;
private Activity mCtx;
private MyAdapter(){} // the adapter won't work with the standard constructor
public MyAdapter(Activity context, int resource, ArrayList<Job> objects)
{
super();
mLayoutID = resource;
mDatalist = objects;
mCtx = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = mCtx.getLayoutInflater();
rowView = inflater.inflate(mLayoutID, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvDescription = (TextView) rowView.findViewById(R.id.textView);
rowView.setTag(viewHolder);
}
ViewHolder vholder = (ViewHolder) rowView.getTag();
TextView tvJob = vholder.tvDescription;
Job myJob = mDatalist.get(position);
tvJob.setText(myJob.getJobDescription());
if (myJob.isDone())
{
// apply changes to TextView
tvJob.setPaintFlags(tvJob.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvJob.setTextColor(Color.GRAY);
}
else
{
// show TextView as usual
tvJob.setPaintFlags(tvJob.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
tvJob.setTextColor(Color.BLACK); // or whatever is needed...
}
return rowView;
}
#Override
public int getCount()
{
return mDatalist.size();
}
#Override
public Object getItem(int position)
{
return mDatalist.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
static class ViewHolder
{
public TextView tvDescription;
}
}
Due to the changed adapter,
in the MainActivity, you have to declare 'items' and 'itemsAdapter' as follows:
private ArrayList<Job> items;
private MyAdapter itemsAdapter;
...and in your 'onCreate()' method, you write:
itemsAdapter = new MyAdapter<String>(this, R.layout.mytextviewlayout, items);
Don't forget to change the 'readItems()' and 'writeItems()' methods because 'items' now is a ArrayList< Job >.
Then, finally, the 'onItemLongClick()' method:
EDIT use 'parent.getItemAtPosition()' instead of 'items.get()', see comments
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
// items.get(position).setDone(true);
Object o = parent.getItemAtPosition(position);
if (o instanceof Job)
{
((Job) o).setDone(true);
}
// and now indeed the data set has changed :)
itemsAdapter.notifyDataSetChanged();
writeItems();
return true;
}

custom adapter isn't showing any items

This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.

ListVIew not updating onRestoreSaveInstanceState

Here is my method:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
DataBaseHandler handler = new DataBaseHandler(getApplicationContext());
//set the spinner for measurement type
Spinner measurementTypeSpinner = (Spinner) findViewById(R.id.MeasurementTypes);
ArrayAdapter adapter = (ArrayAdapter) measurementTypeSpinner.getAdapter();
int typePos = adapter.getPosition(savedInstanceState.getString("measurementtype"));
measurementTypeSpinner.setSelection(typePos);
//set the spinner for the measurement unit
Spinner measurementUnitSpinner = (Spinner) findViewById(R.id.MeasurementSubValues);
ArrayAdapter arrayAdapter = (ArrayAdapter) measurementUnitSpinner.getAdapter();
int unitPos = arrayAdapter.getPosition(savedInstanceState.getString("measurementunit"));
measurementUnitSpinner.setSelection(unitPos);
//set the value
EditText value = (EditText) findViewById(R.id.unit_value);
value.setText(savedInstanceState.getString("value"));
/**
* The list view stuff
*/
ListView unitsList = (ListView) findViewById(R.id.units_list);
unitsList.setItemsCanFocus(true);
MeasurementType mType = handler.getMeasurementType(savedInstanceState.getString("measurementtype"));
//create the converter
Converter converter = new Converter(MeasurementType.getMeasurementType(savedInstanceState.getString("measurementtype")), savedInstanceState.getString("measurementunit"), savedInstanceState.getString("value"));
//convert the values
ArrayList<Unit> convertedValues = converter.convert();
//set the adapter for the list view
unitAdapter = new UnitListAdapter(this, convertedValues, mType);
unitsList.setAdapter(unitAdapter);
}
Basically, there is another activity with a list of items and when the user checks one, it updates the database setting an int property to 1, so that when the ArrayAdapter goes through an arraylist it picks up the property as 1 and displays it, instead of 0 in which case it doesn't display it.
Now on pressing the back button, both the spinners are populated with the values I stored, the value for the EditText is restored, but the ListView is not updated, yet when I leave the app and come back in, the value that was checked is there in the list...
This says to me that I might need to do something with onStop() and onRestart() could someone please advice me. The comment saying 'the list view stuff' is where I am trying to update the list view, it just isn't working and when I debug it won't go into the restore method at all, which is confusing.
EDIT
public class UnitListAdapter extends ArrayAdapter<Unit> {
private Context context;
private ArrayList<Unit> units;
private MeasurementType type;
public UnitListAdapter(Context context, ArrayList<Unit> units, MeasurementType type) {
super(context, R.layout.unit, R.id.unit_name, units);
this.context = context;
this.units = units;
this.type = type;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.unit, parent, false);
final TextView unitName = (TextView) rowView.findViewById(R.id.unit_name);
final EditText unitValue = (EditText) rowView.findViewById(R.id.unit_value);
if(units.get(position) != null) {
if(units.get(position).getView() == 1) {
unitName.setText(units.get(position).getUnitName());
unitValue.setText(units.get(position).getValue().toString());
} else {
unitName.setVisibility(View.GONE);
unitValue.setVisibility(View.GONE);
}
}
return rowView;
}
#Override
public void add(Unit u) {
units.add(u);
notifyDataSetChanged();
}
#Override
public void clear() {
units.clear();
notifyDataSetChanged();
}
#Override
public int getCount() {
return units.size();
}
}
As asked for. Sorry about confusion whilst editing.
onRestoreInstanceState() is not called when the user presses the back button. Most likely you need to move your logic to onResume(). I suggest that you read about the Activity lifecycle to get a better understanding about when each of the onXxx() methods are called.
After updating the list you need to call notifyDataSetChanged() to repopulate the listview.
http://developer.android.com/reference/android/widget/ArrayAdapter.html#notifyDataSetChanged()

Categories

Resources