0

I'm trying to add items to a listview via a textbox without sub items in the list.What I have found so far relating to this is this Dynamically add elements to a listView Android but I'm using fragements so I'm getting the folllowing errors when implementing this solution,http://pastebin.com/1QrUTx15

This is how I tried to implement it but I think its not working because I'm using two onCreate methods.Can someone shed someone point me in the right direction with this issue or if there is a better way of adding items from a textbox to a listview? I'm wondering also how I would exclude sub items from the listview so that just the item is passed to it.

public class TopRatedFragment extends Fragment {

    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

  //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
        return rootView;
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.fragment_top_rated);
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }

}

This is what the interface looks like at present..

enter image description here

Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212

1 Answers1

0

Either assign a new Adapter to your ListView once you have added a new item:

public void addItems(View v) {
    listItems.add("Clicked : "+clickCounter++);
    adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
    setListAdapter(adapter);
}

Or use a custom ListView Adapter. Only then, you can use notifyDataSetChanged. I explained details about that in an answer to a similar question: Android - Dynamically Updating a custom ListView after items in an ArrayList are added

Community
  • 1
  • 1
FD_
  • 12,947
  • 4
  • 35
  • 62