0

我正在尝试使用测试值实现 ListView。每个列表元素应该显示 2 个字符串。但我得到一个 NullPointerException。

我有一个 ListActivity,调用一个适配器。如果我评论这个活动的最后一行,我没有任何错误,所以我猜我的适配器有问题。但是我在网上搜索了解决方案,不幸的是,由于 Java(和 OOP)技能非常低,我无法解决我的问题。你能告诉我我在哪里犯了错误吗?

public class ListActivity extends Activity {

//private final String TAG = ListActivity.class.getSimpleName();
private ListView listMessView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    List<Message> listMessages = new ArrayList<Message>();
    listMessages.add(new Message("London", "aze"));
    listMessages.add(new Message("Rome", "azeeaze"));
    listMessages.add(new Message("Paris", "qsdqsdqsd"));

    listMessView =  (ListView) findViewById(R.id.message_list);
    listMessView.setAdapter(new ListAdaptater(this, R.layout.list_row, listMessages));
    }
}


public class ListAdaptater extends ArrayAdapter<Message>{

  private int resource;
  private LayoutInflater inflater;
  private Context context;

  public ListAdaptater ( Context ctx, int resourceId, List<Message> objects) {

        super( ctx, resourceId, objects );
        resource = resourceId;
        inflater = LayoutInflater.from( context );
        context=ctx;
  }

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

        convertView = ( RelativeLayout ) inflater.inflate( resource, null );

        Message message = (Message) getItem( position );

        TextView txtName = (TextView) convertView.findViewById(R.id.user_name);
        txtName.setText(message.getUserName());

        TextView txtMsg = (TextView) convertView.findViewById(R.id.message);
        txtMsg.setText(message.getMessage());

        return convertView;
  }
  }
4

1 回答 1

1

该字段context在初始化之前使用。尝试使用这个:

  public ListAdaptater ( Context ctx, int resourceId, List<Message> objects) {

        super( ctx, resourceId, objects );
        resource = resourceId;
        inflater = LayoutInflater.from( ctx );
        context=ctx;
  }
于 2013-01-13T18:35:16.183 回答