1

Hello I'm currently trying to make my first app on android and I've gotten some problems. I'm trying to make a todo-list app so want some kind of input to be transformed into checkboxes. I've made it work with radio buttons using radioGroup. But when using Checkboxes with ListView it just doesn't work.

Here's my code:

public class MainActivity extends AppCompatActivity {

EditText t;
ListView listView;
ArrayList<CheckBox> checkList = new ArrayList<>();
int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void add(View view){

    t = findViewById(R.id.input);
    String s = t.getText().toString();

    CheckBox check = new CheckBox(this);
    checkList.add(check);

    listView = findViewById(R.id.list);

    checkList.get(i).setText(s);
    listView.addView(checkList.get(i));


    i++;
    t.setText("");

}}

The app crashes saying something about adapterView

NZX
  • 19
  • 2

1 Answers1

0

You're unfortunately doing something wrong here. You are trying to add your view to Listviews on

listView.addView(checkList.get(i));

This is not the correct way to use ListViews. You have to use an adapter. The adapter would need to provide data for the listview to load.

Please have a look at this tutorial for how to use listviews.

Below is a summary of the steps to use a listView correctly.

  • Create a new layout file (say custom_cell.xml) inside your layouts folder.
  • Insert a checkbox inside your custom_cell.xml and place an Id which you can use later to identify the checkbox
  • Create an adapter for your listview
  • Override the getView method
  • Inside the getView method, inflate a new cell using the custom_cell.xml or reuse an existing cell if provided
  • Reference the Checkbox by using the Id you provided in the custom_cell.xml file
Ruchira Randana
  • 4,021
  • 1
  • 27
  • 24
  • Is it a must to write all the code inside the protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } or is it ok to put it below as I did? – NZX Nov 09 '18 at 13:52
  • Hi @NZX: The problem is not where you have inserted the code. You can not use a listview without using an adapter. Specifically saying, the line of code "listView.addView(checkList.get(i));" is wrong. You can not add a view like this to a listview. I'll define the correct way in my answer. – Ruchira Randana Nov 09 '18 at 14:23