ListView和NullPoinerException,我不明白

时间:2013-01-13 18:31:29

标签: android listview nullpointerexception adapter

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

我有一个ListActivity,调用一个Adapter。如果我评论此活动的最后一行,我没有任何错误,所以我猜我的调整器有错误。但我在网上搜索过解决方案,不幸的是,由于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;
  }
  }

1 个答案:

答案 0 :(得分:1)

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

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

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