On every button click data is added to listview but in an unexpected manner . Data is repeated in the listview

StackOverflow https://stackoverflow.com/questions/19900937

  •  30-07-2022
  •  | 
  •  

Question

[Activity]
public class MainActivity : Activity
{
  public string[] items = new string[100];    // string to store data from editText
  int i =0;
  ArrayAdapter<string > adapter;
  protected override void OnCreate(Bundle savedInstance) 
  {
    base.OnCreate(savedInstance);
    SetContentView(R.Layouts.MainLayout);

    var btn1= FindViewById <Button> (R.Ids.btn1);
    btn1.Click += AddItem;    // calls a function on button click to add data to listview
  }

  public void AddItem(object sender,EventArgs eventargs)
  {
    try
    {
      var et1 = FindViewById <EditText>(R.Ids.et1);
      items[i] = et1.Text.ToString();
      i++;
      view();    //to add data to listview
    }

    catch(Exception ex)
    {
      error(ex.ToString());
    }
  }

  public void view ()
  {
    adapter = new ArrayAdapter<string>(GetApplicationContext(),Android.R.Layout.Simple_list_item_1,items);
    ListView listview = FindViewById<ListView>(R.Ids.listview1);
    listview.SetAdapter(adapter);
    listview.SetTextFilterEnabled(true);

    }
  }
Was it helpful?

Solution

You should not call view() from AddItem because all code in view is initialization code. Rename it initList or so and call it from OnCreate.

You also don't need items (or i). Just add the string to adapter.

-- EDIT

[Activity]
public class MainActivity : Activity
{
   private ArrayAdapter<string> adapter;

   protected override void OnCreate(Bundle savedInstance)
   {
      base.OnCreate(savedInstance);
      SetContentView(R.Layouts.MainLayout);

      ListView list = FindViewById<ListView>(R.Ids.list);
      adapter = new ArrayAdapter<string>(this, Android.R.Layout.Simple_list_item_1);
      list.SetAdapter(adapter);

      Button button = FindViewById<Button>(R.Ids.button);
      button.Click += button_Click;
   }

   void button_Click(object sender, EventArgs e)
   {
      EditText text = FindViewById<EditText>(R.Ids.text);
      adapter.Add(text.Text.ToString());
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top