Как отправить данные элемента списка пользовательского массива при нажатии на другое действие?

У меня есть список массивов пользовательских объектов Song, и я хочу отправить название песни, имя исполнителя и изображение обложки альбома в другое действие (Song Activity) при нажатии определенного элемента песни в списке. Я создал SongActivity для отображения текущего экрана воспроизведения песни, которую выбрал пользователь.

(ЗАДАНИЕ ПО СПИСКУ ПЕСЕН) Содержит список песен.

 public class SongsListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.songs_list);
    ArrayList<Song> songs = new ArrayList<Song>();
            songs.add(new Song("Earthquake","Marshmello and TYNAN",R.mipmap.earthquake));
        .....

            final SongAdapter adapter = new SongAdapter(this, songs);


            ListView listView = findViewById(R.id.list);

            listView.setAdapter(adapter);

            ListView listview = (ListView) findViewById(R.id.list);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Intent intent = new Intent(view.getContext(), SongActivity.class);

                }
            });

        }
    }

(ПЕСНЯ) Это действие начинается, когда пользователь щелкает конкретный объект песни.

import androidx.appcompat.app.AppCompatActivity;

public class SongActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.song_activity);
        ImageView songImage = findViewById(R.id.songImage);
        TextView songName = findViewById(R.id.songName);
        TextView artistName = findViewById(R.id.artistName);

        Intent intent = getIntent();

        songImage.setImageResource(intent.getIntExtra("image",0));
        songName.setText(intent.getStringExtra("songName"));
        artistName.setText(intent.getStringExtra("artistName"));

    }
}

(АДАПТЕР ПЕСНИ)

public class SongAdapter extends ArrayAdapter {

    public SongAdapter(Activity context, ArrayList<Song> songs) {

        super(context, 0, songs);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }


        Song currentSong = (Song) getItem(position);

        TextView nameTextView = (TextView) listItemView.findViewById(R.id.song_name);

        nameTextView.setText(currentSong.getSongName());

        TextView artistTextView = (TextView) listItemView.findViewById(R.id.artist_name);

        artistTextView.setText(currentSong.getArtistName());

        ImageView iconView = (ImageView) listItemView.findViewById(R.id.song_icon);

        iconView.setImageResource(currentSong.getImageResourceId());

        return listItemView;
    }

}

Вам нужно упаковать вашу пользовательскую модель, а затем отправить ее с помощью намерения. намерение.putParcelableArrayListExtra (Intent.EXTRA_STREAM, mMenuScreenShotList)

Anas Mehar 27.07.2019 10:30

отредактируйте свой вопрос, проверьте его.

Anas Mehar 27.07.2019 11:07
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
2
2
600
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Парацелизируйте свой модал, как это

    public class Student implements Parcelable {

    private Integer rollno;
    private String name;
    private Integer age;


    protected Student(Parcel in) {

        age = in.readInt();
        name  = in.readString();
        rollno = in.readInt();

    }

    public Student(Integer age, String name, Integer rollno) {
        this.age = age;
        this.name = name;
        this.rollno = rollno;
    }


    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };


    @Override
    public int describeContents() {
        return 0;
    }

    public Integer getRollno() {
        return rollno;
    }

    public void setRollno(Integer rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }



    public static Creator<Student> getCREATOR() {
        return CREATOR;
    }


  @Override
    public void writeToParcel(Parcel parcel, int i) {

        parcel.writeInt(age);
        parcel.writeString(name);
        parcel.writeInt(rollno);


    }
}

And then set and get using intent

intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, studentList) 
intents.getParcelableArrayList<Student>(Intent.EXTRA_STREAM)

Какой класс я должен разделить? И как мне его назвать, чтобы я получил название песни, имя исполнителя и связанное с ним изображение в SongActivity и заставил его отображать TextViews и ImageView соответственно. Было бы очень полезно, если бы вы могли предоставить код. Спасибо!

Vihaan Misra 27.07.2019 10:42

Вам нужно разделить модальный класс вашей песни на части.

Anas Mehar 27.07.2019 10:51
Ответ принят как подходящий

Ваша модель песни (класс) должна выглядеть так


    import android.os.Parcel;
    import android.os.Parcelable;

    public final class Songs implements Parcelable {
        public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
            @Override
            public Songs createFromParcel(final Parcel source) {
                return new Songs(source);
            }

            @Override
            public Songs[] newArray(final int size) {
                return new Songs[size];
            }
        };
        private String songName;
        private String artistName;
        private Integer imageId;

        public Songs() {
        }

        public Songs(final String songName, final String artistName, final Integer imageId) {
            this.songName = songName;
            this.artistName = artistName;
            this.imageId = imageId;
        }

        protected Songs(final Parcel in) {
            this.songName = in.readString();
            this.artistName = in.readString();
            this.imageId = (Integer) in.readValue(Integer.class.getClassLoader());
        }

        public String getSongName() {
            return songName;
        }

        public void setSongName(final String songName) {
            this.songName = songName;
        }

        public String getArtistName() {
            return artistName;
        }

        public void setArtistName(final String artistName) {
            this.artistName = artistName;
        }

        public Integer getImageId() {
            return imageId;
        }

        public void setImageId(final Integer imageId) {
            this.imageId = imageId;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(final Parcel dest, final int flags) {
            dest.writeString(this.songName);
            dest.writeString(this.artistName);
            dest.writeValue(this.imageId);
        }
    }

В вашем SongListActivity


    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView parent, View view, int position, long id) {

                    Intent intent = new Intent(view.getContext(), SongActivity.class);
                    intent.putExtra("SONG_DATA", songList.get(position));
                    startActivity(intent);
                }
            });

И, наконец, в onCreate() вашего SongActivity вы должны получить намерение и получить данные, например

if (getIntent() != null) {
    Song song = getIntent().getParcelableExtra("SONG_DATA");
    // now you have got song object, You can do rest of operations
}

Чтобы сделать любую модель данных Parcelable, просто добавьте плагин Parcelable в свою студию Android из меню settings->Plugins. Затем внутри вашего класса данных просто нажмите alt+insert и выберите Parcelable, Плагин создаст для вас код Parcelable.

Rakshith Shetty 27.07.2019 11:12

Данные передаются сейчас, но когда я запускаю приложение, оно вылетает.

Vihaan Misra 27.07.2019 11:36

java.lang.RuntimeException: невозможно запустить активность android.widge‌​t.AdapterView$OnItem‌​ClickListener)' для нулевой ссылки на объект

Vihaan Misra 27.07.2019 11:37

ваш listView равен нулю. убедитесь, что findViewById(R.id.list); не возвращает значение null.

Rakshith Shetty 27.07.2019 12:06

Другие вопросы по теме