Home > Net >  how to add an item to a listView whithout changing other Items
how to add an item to a listView whithout changing other Items

Time:03-19

I'm beginner in android and i want to add an item to a ListView when i click on a button. but when i do that , the ListView restarts and all the previous changes i made disappear. how can i save the previous state of the ListView.

This is the MainActivity : 

            protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listMarks = (ListView) findViewById(R.id.list_marks);
btn_add = (Button) findViewById(R.id.btn_add);
final Mark mark = new Mark("", "", "", "");
final ArrayList<Mark> marks = new ArrayList<Mark>();
marks.add(marks.size(), mark);
adapter = new MarkLitViewAdapter(MainActivity.this, marks);
listMarks.setAdapter(adapter);
btn_add.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    marks.add(mark);
    adapter.notifyDataSetChanged();
  }
});

}

I made this changes but when click on add button an item is being add but previous changes disappear this is when i click on the add button

CodePudding user response:

Instead of doing adapter.insert(mark, marks.size()); you can use the adapter.notifyDataSetChanged(); functionality. Remove the final from here final ArrayList<Mark> marks = new ArrayList<Mark>(); and insert your Mark into this ArrayList and then do adapter.notifyDataSetChanged() inside the OnClickListener

CodePudding user response:

First off, I strongly suggest you use RecyclerView instead of ListView, if you aren't already. It's a categorically better version of ListView.

The function you are looking for is notifyItemInserted.

I wrote up a very simple example in Kotlin (also suggested learning if you want to continue in Android development, since it's the officially supported language now.)

The relevant snippet is below. Create an addItem function in your adapter which uses notifyItemInserted:

fun addItem(value: String) {
    items.add(value)
    notifyItemInserted(items.size)
}

And then in your button OnClickListener call that adapter function to add a new item.

  • Related