ListAdapter抛出错误:null对象引用

时间:2016-02-28 19:50:18

标签: java android listadapter

我收到以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sebastian.codivatemanager.User.getName()' on a null object reference
at com.sebastian.codivatemanager.FriendAdapter.getView(FriendAdapter.java:57)

在这堂课上:

public class FriendAdapter extends BaseAdapter {

private Context mContext;
private User[] mUsers;

public FriendAdapter(Context context, User[] users) {
    mContext = context;
    mUsers = users;
}

@Override
public int getCount() {
    return mUsers.length;
}

@Override
public Object getItem(int position) {
    return mUsers[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if(convertView == null) {
        //brand new
        convertView = LayoutInflater.from(mContext).inflate(R.layout.user_overview, null);
        holder = new ViewHolder();
        holder.nameLabel = (TextView) convertView.findViewById(R.id.textViewName);
        holder.levelLabel = (TextView) convertView.findViewById(R.id.textViewLevel);

        convertView.setTag(holder);
    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }

    User user = mUsers[position];

    holder.nameLabel.setText(user.getName());
    holder.levelLabel.setText(user.getLevel() + "");

    return convertView;
}

private static class ViewHolder {
    TextView nameLabel;
    TextView levelLabel;
}
}

指出的一行是:

holder.nameLabel.setText(user.getName());

我正在尝试使用列表适配器“FriendAdapter”显示列表。这个列表来自一个名为“mUsers”的数组,它从包含在它的类中继承:

            User[] mUsers = new User[array.length() + 1];

        for(int n = 0; n < array.length(); n++) {
            JSONObject obj = array.getJSONObject(n);
            Log.i("Friends", obj.toString());
            mUsers[n] = new User();
            mUsers[n].setName(obj.getString("name"));
            mUsers[n].setLevel(obj.getDouble("level"));
        }

        FriendAdapter adapter = new FriendAdapter(this, mUsers);
        setListAdapter(adapter);

0 个答案:

没有答案