简体   繁体   中英

NullPointerException upon using ArrayList<String>

In the given code below, I get a NullPointerException when I include the for block so as to use the ArrayList words in the ArrayAdapter constructor. However, if I remove the for block and instead use the String array strArray , it works just fine.

Could anyone tell me why is that so?

 import java.util.ArrayList;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.ArrayAdapter;
 import com.actionbarsherlock.app.SherlockListFragment;

 public class ShowList extends SherlockListFragment 
 {
    private static final String[] strArray={"this","one","is","an","experimental","list"};
    ArrayList<String> words; 
    ArrayAdapter<String> adapter;
    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {

    super.onActivityCreated(savedInstanceState);

    for(String s: strArray)
    {

        words.add(s);

    }

    adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,words);
    Log.d("Action","before setListAdapter"); 
    setListAdapter(adapter);
}

The code that works fine is below:

 public class ShowList extends SherlockListFragment 
 {
     private static final String[] strArray={"this","one","is","an","experimental","list"};
    ArrayList<String> words; 
    ArrayAdapter<String> adapter;
    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {

         super.onActivityCreated(savedInstanceState);

/*  for(String s: strArray)
    {

        words.add(s);

    }
*/
    adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,strArray);
    Log.d("Action","before setListAdapter"); 
    setListAdapter(adapter);
}

}

您需要初始化目标词。

words= new ArrayList<String>();

words is unitialized, but you add objects to it.

You must do

words = new ArryList<String>();

before you enter the loop.

And I would get used to declare such a variable as

List<String>words

instead of

ArrayList<String>words.

List is in interface, and you can pass arbitrary lists to other functions, but if you specify ArrayList specifically, you can only pass that kind of lists. For this exmaple it doesn't matter though.

Initialize you ArrayList words; first:

private ArrayList<String> words = new ArrayList<String>();  

And also

private static final String[]strArray{"this","one","is","an","experimental","list"};

seems not compiled. change it to:

private static final String[] strArray =  {"this", "one", "is", "an", "experimental", "list"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM