调用notifydatasetchanged时,在自定义listview适配器中获取nullpointerexception

时间:2013-02-15 05:10:19

标签: android

我想问一些帮助,为什么我在调用notifyDataSetChanged之后得到一个空指针异常。但我之前可以添加数据。下面是我收到错误的代码。

public class MyFragment extends SherlockFragment {
private ListView subjectList;
private ArrayList<String> stringArray;
private ArrayAdapter<String> adapter;
private View view;

public MyFragment() {       
}   

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    stringArray = new ArrayList<String>();                  
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.activity_subjects, null);
    subjectList = (ListView)view.findViewById(R.id.subjectList);         

    //Log.v("MyFragment", "onCreateView");
    stringArray.add("test 1");

    return view;                
}

 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
     super.onActivityCreated(savedInstanceState);                

     Log.v("MyFragment", "onActivityCreated");
     adapter = new SubjectAdapter(getSherlockActivity(), stringArray);
     subjectList.setAdapter(adapter);
 }

@Override
public void onStart() {
    super.onStart();

    Log.v("MyFragment", "onStart");     
}

@Override
public void onResume() {
    super.onResume();
}

public void updateList(JSONArray jsonArray) {
    //adapter.clear();
    for(int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            stringArray.add(jsonObject.getString("subjectname"));
            Log.v("MyFragment", "stringArray: " + stringArray.toString());              
        }           
        catch(JSONException e) {
            e.printStackTrace();
        }

        adapter.notifyDataSetChanged();
    }
}
}

似乎适配器为空。你有人可以给我建议吗?

抱歉不要包含适配器。这是我的适配器。

public class SubjectAdapter extends ArrayAdapter<String> {
private Context context;
private ArrayList<String> values = new ArrayList<String>();

public SubjectAdapter(Context context, ArrayList<String> values) {
    super(context, R.layout.activity_row_layout, values);
    this.context = context;
    this.values = values;       
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //Log.v("adapter","yes");
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.activity_row_layout, parent, false);
    TextView textView = (TextView)rowView.findViewById(R.id.subject_item_name);

    textView.setText(values.get(position));

    return rowView;
}
}

0 个答案:

没有答案