-1

在下面给定的代码中,NullPointerException当我包含for 块以便在 ArrayAdapter 构造函数中使用ArrayList 字时,我得到一个。但是,如果我删除for 块并改用字符串数组 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);
}

}

4

3 回答 3

3

您需要初始化对象词。

words= new ArrayList<String>();
于 2013-07-14T07:05:29.430 回答
2

words是未初始化的,但是您向其中添加了对象。

你必须做

words = new ArryList<String>();

在你进入循环之前。

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

List<String>words

代替

ArrayList<String>words.

List在接口中,您可以将任意列表传递给其他函数,但是如果您特别指定ArrayList,则只能传递那种列表。对于这个例子,这并不重要。

于 2013-07-14T07:06:18.800 回答
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"};
于 2013-07-14T07:18:03.600 回答