title: Android ListView.setOnItemClickListener NullPointerException when there are more items then the screen can hold
body: <p>When this ListView has more items then can be shown on the screen (you have to scroll to see the others) and you select one of the items I get a NullPointerException</p>
  
  <p>Here is the code:</p>
  
  <pre><code>studentList = (ListView)findViewById(R.id.studentListView);
  getAllStudents();
  studentList.setOnItemClickListener(new OnItemClickListener(){
       @Override
       public void onItemClick(AdapterView&lt;?&gt; a, View v, int position, long id) {
  
          for (int i = 0; i &lt; studentList.getCount(); i++){
  
                  if (i == position){
                      studentList.getChildAt(i).setBackgroundResource(R.color.selectedListViewBg);
                  }
                  else{
                      studentList.getChildAt(i).setBackgroundResource(R.color.listViewBg);
                  }   
  
              }
  </code></pre>
  
  <p>To pull the students from the database and add them to the studentList ArrayAdapter:</p>
  
  <pre><code>getAllStudents(); 
  </code></pre>
  
  <p>I get the Exception at: </p>
  
  <pre><code>studentList.getChildAt(i).setBackgroundResource(R.color.&lt;either one&gt;);
  </code></pre>
  
  <p>If the ListView can hold all the items without having to scroll, you can select without the NullPointerException</p>
  
  <p>What am I doing wrong?</p>
  
  <p><strong>EDIT :</strong></p>
  
  <p>After reading the answers to this question, I decided to change the logic at this part of my program.</p>
  
  <p>I probably should have explained what I was trying to do better:</p>
  
  <p>I have a ListView that is populated with students. There is also a button at the bottom that says "Next".  I wanted the user to be able to click on their choice and have the background color change. This section of code was supposed to change the selected item's background to one color and all the other item's backgrounds back to the original color.</p>
  
  <p><strong>My Solution:</strong>
  I got rid of the button and move on to the next page when the user clicks on the ListView item.</p>