使用ArrayList <string> </string>时出现NullPointerException

时间:2013-07-14 07:02:20

标签: java nullpointerexception runtime-error

在下面给出的代码中,当我包含 for block 时,我得到NullPointerException,以便使用 ArrayList字词 在ArrayAdapter构造函数中。但是,如果我删除了 for block ,而是使用 String array strArray ,它就可以了。

有谁可以告诉我为什么会这样?

 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);
}

工作正常的代码如下:

 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);
}

}

3 个答案:

答案 0 :(得分:3)

您需要初始化对象词。

words= new ArrayList<String>();

答案 1 :(得分:2)

words是单元化的,但您可以向其添加对象。

你必须

words = new ArryList<String>();

进入循环之前。

我会习惯将这样的变量声明为

List<String>words

而不是

ArrayList<String>words.

List在界面中,您可以将任意列表传递给其他函数,但如果您具体指定ArrayList,则只能传递这种列表。对于这个例子,它并不重要。

答案 2 :(得分:0)

初始化ArrayList单词;第一:

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

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

似乎没有编译。将其更改为:

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