自定义适配器 getView returns 空指针

Custom adatper getView returns null pointer

在我的应用程序中,我有一个带有自定义适配器的列表视图,它会在发送消息后重新加载。该应用程序在某些安装时崩溃。我在应用程序控制台中有堆栈跟踪。这里的代码:

class IconicAdapter extends ArrayAdapter<Integer> {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.message_layout, listItems);

            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {


                //you can access layout inflater by accessing hosting activity
                convertView = getActivity().getLayoutInflater().inflate(R.layout.message_layout, parent, false);


            JSONObject json_data = null;
            try {
                json_data = jArray.getJSONObject(position);
            } catch (JSONException e) {
            }

            try {
                tv = (TextView) convertView.findViewById(R.id.username);
                tv.setText(json_data.getString("username"));

此处堆栈跟踪:

java.lang.NullPointerException: 
  at com.testing.gold.CommunityFragment$IconicAdapter.getView (CommunityFragment.java:945)
  at android.widget.HeaderViewListAdapter.getView (HeaderViewListAdapter.java:232)

第 945 行:tv.setText(json_data.getString("username"));

class IconicAdapter extends ArrayAdapter<Integer> {
   Activity context;

   IconicAdapter(Activity context) {
    super(context, R.layout.activity_main, new Integer[]{1, 2});
    this.context = context;
}

public View getView(int position, View convertView, ViewGroup parent) {

    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, null);
    JSONObject json_data = null;
    try {
        json_data = jArray.getJSONObject(position);
        tv = (TextView) convertView.findViewById(R.id.username);
        tv.setText(json_data.getString("username"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return convertView;
}

}

使用以下代码: class IconicAdapter 扩展 ArrayAdapter { Activity 上下文;

IconicAdapter(Activity context) {
    super(context, R.layout.message_layout, listItems);

    this.context = context;
}

public View getView(int position, View convertView, ViewGroup parent) {
     convertView=LayoutInflater.inflate(R.layout.message_layout, null);
     JSONObject json_data = null;
     try {
        json_data = jArray.getJSONObject(position);

    } catch (JSONException e) {
         e.printStackTrace();
    }
 tv = (TextView) convertView.findViewById(R.id.username);

if(json_data!=null)
   tv.setText(json_data.getString("username"));
else
   tv.setText("")