自定义adatper getView返回空指针

时间:2017-11-16 22:36:02

标签: android custom-adapter getview

在我的应用程序中,我有一个listview,其中包含一个自定义适配器,在发送消息后重新加载。该应用程序在某些安装中崩溃。我在app控制台中有堆栈跟踪。代码如下:

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

2 个答案:

答案 0 :(得分:1)

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

}

答案 1 :(得分:1)

使用以下代码:       class IconicAdapter extends ArrayAdapter {     活动背景;

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("")