Android adapter.getItem(position).getItemId() не работает (метод getId() не определен для типа Object)

У меня есть просмотр списка, и я заполняю данные в форме представления списка БД, используя пользовательский адаптер. Работает нормально, но когда я нажимаю на элемент списка, я хочу получить идентификатор элемента, по которому щелкают, чтобы передать его следующему действию, чтобы сделать что-то. Но когда я нажимаю на элемент списка, я не могу получить идентификатор. Есть идеи, почему это происходит?

мой список слушателей:

    list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> a, View view, int position,
                        long id) {


                    Intent intent = new Intent(MainActivity.this,
                            CountryActivity.class);
                     intent.putExtra("countryId", adapter.getItem(position).getId());//here i am getting error saying 
          //The method getId() is undefined for the type Object.

                    startActivity(intent);

                }
            });

Но я определил свой country.java (POJO) для спецификации типа

public class Countries {
    Integer id;
    String countryName = "", countryIcon = "";

    public Countries(Integer id, String countryName, String countryIcon) {

        this.id = id;
        this.countryName = countryName;
        this.countryIcon = countryIcon;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public String getCountryIcon() {
        return countryIcon;
    }

    public void setCountryIcon(String countryIcon) {
        this.countryIcon = countryIcon;
    }

}

я выбираю данные из курсора obj (визы) из приведенного ниже кода:

names = new ArrayList<Countries>();
        do {

            country = new Countries(Integer.parseInt(visas.getString(0)),
                    visas.getString(1), visas.getString(2));

            // Log.d("VISA", visas.getString(0));

            names.add(country);

        } while (visas.moveToNext());

вот мой код адаптера:

public class VisaAdapter extends ArrayAdapter<Countries> {
    private final Context context;
    private final ArrayList<Countries> values;
    Resources resc = getContext().getResources();

    public VisaAdapter(Context context, ArrayList<Countries> values) {
        super(context, R.layout.list_item, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public Countries getItem(int position) {
        return values.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.list_item, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
        textView.setText(values.get(position).getCountryName());

        // Change icon based on name
        String icon = values.get(position).getCountryIcon();
        int resIcon = resc.getIdentifier(icon, "drawable", "com.m7.visaapp");

        rowView.setBackgroundResource(R.drawable.list_view_places_row);

        imageView.setImageResource(resIcon);

        return rowView;
    }

}

2 ответа

Решение

Вы должны разыграть getItem(position) вернуть значение в Countries объект.

Изменить это:

    intent.putExtra("countryId", adapter.getItem(position).getId());

К этому:

    Countries countries = (Countries)adapter.getItem(position);
    intent.putExtra("countryId", countries.getId());

Обновление:

На самом деле, после прочтения комментария @Tushar, я думаю, вы должны сделать names VisaAdapter вместо ArrayList<Countries>(), Тогда ваша оригинальная строка кода, приведенная выше, должна работать как есть.

adapter.getItem(position)

Функция возвращает Object так что типа приведите его к стране, как

(Countries)adapter.getItem(position)
Другие вопросы по тегам