在下面给定的代码中,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);
}
}