简体   繁体   中英

Passing the data associated to a ListView cell to another activity onClick() of the item

I am new to android programming. I am writing a simple music app using ListView and a custom layout. Each row in the list has two TextView's for song name and artist name.

I have two activities, MainActivity and nowPlaying Activity, there is list on nowPlaying Activity that also has two TextView's . What I want to achieve is, when I click on an item on the ListView (in Main Activity), I want to get the song name and artist name and set it to the TextView's in the nowPlaying Activity.

MainActivity

public class MainActivity extends AppCompatActivity {

ListView listView;
ArrayList<Songs> song;

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

    song = new ArrayList<Songs>();
    song.add(new Songs("Shape of you", "ed sheeran", "4:59"));
    song.add(new Songs("Energy", "avelino", "3:15"));
    song.add(new Songs("Wages", "bad sounds", "2:56"));
    song.add(new Songs("L'Hiver Indien", "baloji", "3:28"));
    song.add(new Songs("Faded Heart", "Borns", "4:59"));
    song.add(new Songs("King Ruby", "ider", "4:59"));
    song.add(new Songs("Drown", "kovic", "4:59"));
    song.add(new Songs("Supercut", "lorde", "4:59"));
    song.add(new Songs("&Run", "sir sly", "4:59"));
    song.add(new Songs("Live in the moment", "portugal. the man", "4:59"));

    SongAdapter adapter = new SongAdapter(this, song);

    listView = findViewById(R.id.list_view);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            TextView songName = findViewById(R.id.song_name);
            TextView artistName = findViewById(R.id.artist);
            Intent intent = new Intent(MainActivity.this, nowPlaying.class);
            intent.putExtra("name", listView.getItemAtPosition(i).toString());
            startActivity(intent);
        }
    });
    listView.setAdapter(adapter);
}

}

SongAdapter

public class SongAdapter extends ArrayAdapter<Songs> {


public SongAdapter(Activity context, ArrayList<Songs> song) {
    // Here, we initialize the ArrayAdapter's internal storage for the context and the list.
    // the second argument is used when the ArrayAdapter is populating a single TextView.
    // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
    // going to use this second argument, so it can be any value. Here, we used 0.
    super(context, 0, song);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    //return super.getView(position, convertView, parent);
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.song_item, parent, false);
    }

    Songs currentSong = getItem(position);

    TextView songName = listItemView.findViewById(R.id.song_name);
    songName.setText(currentSong.getSongName());

    TextView artistName = listItemView.findViewById(R.id.artist);
    artistName.setText(currentSong.getArtistName());

    TextView time = listItemView.findViewById(R.id.time);
    time.setText(currentSong.geTime());

    return listItemView;
}
}

Screenshot

In the screenshot (given above), each row has a name for song and another for artist. When the row is clicked, I want to get the name and set it on the other activity and do same for artist name.

I want this to happen for each item in the ListView .

SongsClass

public class Songs {
private String mSongName;
private String mArtistName;
private String mTime;

public Songs(String songName, String artistName, String Time) {
    mSongName = songName;
    mArtistName = artistName;
    mTime = Time;
}

public String getSongName() {
    return mSongName;
}
public String getArtistName() {
    return mArtistName;
}

public String geTime() {
    return mTime;
}

}

Note Just make Songs model class with getter and setter of songName and artistName And just get data in NowPlayingActivcty by intent

public class MainActivity extends AppCompatActivity {

ListView listView;
ArrayList<Songs> song;

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

  final song = new ArrayList<Songs>();
    song.add(new Songs("Shape of you", "ed sheeran", "4:59"));
    song.add(new Songs("Energy", "avelino", "3:15"));
    song.add(new Songs("Wages", "bad sounds", "2:56"));
    song.add(new Songs("L'Hiver Indien", "baloji", "3:28"));
    song.add(new Songs("Faded Heart", "Borns", "4:59"));
    song.add(new Songs("King Ruby", "ider", "4:59"));
    song.add(new Songs("Drown", "kovic", "4:59"));
    song.add(new Songs("Supercut", "lorde", "4:59"));
    song.add(new Songs("&Run", "sir sly", "4:59"));
    song.add(new Songs("Live in the moment", "portugal. the man", "4:59"));

    SongAdapter adapter = new SongAdapter(this, song);

    listView = findViewById(R.id.list_view);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            TextView songName = findViewById(R.id.song_name);
            TextView artistName = findViewById(R.id.artist);
            Intent intent = new Intent(MainActivity.this, nowPlaying.class);
            intent.putExtra("songName", listView.get(i).getsongName());
            intent.putExtra("artistName", listView.get(i).getartistName());
            startActivity(intent);
        }
    });
    listView.setAdapter(adapter);
}

你在做正确的事情,你需要添加的只是演员的名字和艺术家,然后从第二个活动中取回他们

here how to fix onClick if you need to send object of songs search for how to turn your songs class to parcelable

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
       String song_name= song.get(i).getSongName().toString();
        Intent intent = new Intent(MainActivity.this, nowPlaying.class);
        intent.putExtra("name",song_name );
        startActivity(intent);
    }
});
enter code here

Change this (listView.getItemAtPosition(i).toString()) by songName or artistName.

and get it in your sencond activity.

You want to pass some data (in your case song name and artist name ) to some other activity. So this can be achieved by passing the desired data through intents because intents are messaging objects and you can wraps small chunks of data into to them to be passed between activities. So the code for the same is:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            TextView songName = view.findViewById(R.id.song_name);
            TextView artistName = view.findViewById(R.id.artist);
            Intent intent = new Intent(MainActivity.this, nowPlaying.class);
            intent.putExtra("song_name", songName.getText().toString());
            intent.putExtra("artist_name", artistName.getText().toString());
            startActivity(intent);
        }
    });

The view given in the onItemClick() method is the view which was clicked (returned by the adapter) so you get its contents and pass it forward to the other activity as it is.

Alternative way:

You cannot access the song list(Array list of songs) inside onItemCLick() unless its declared as final . So you can declare it as follows and access it:

final ArrayList<Songs> songs = new ArrayList<Songs>() {{
    add(new Songs("Shape of you", "ed sheeran", "4:59"));
    add(new Songs("Energy", "avelino", "3:15"));
    add(new Songs("Wages", "bad sounds", "2:56"));
    add(new Songs("L'Hiver Indien", "baloji", "3:28"));
    add(new Songs("Faded Heart", "Borns", "4:59"));
    add(new Songs("King Ruby", "ider", "4:59"));
    add(new Songs("Drown", "kovic", "4:59"));
    add(new Songs("Supercut", "lorde", "4:59"));
    add(new Songs("&Run", "sir sly", "4:59"));
    add(new Songs("Live in the moment", "portugal. the man", "4:59"));
}}

Now you can use this song list to get the data in onItemClick() method as follows:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(MainActivity.this, nowPlaying.class);
                intent.putExtra("song_name", songs.get(i).getSongName()); // Note: If the getters are not set to get the song name and artist name then they need to be set to use this approach
                intent.putExtra("artist_name", songs.get(i).getArtistName());
                startActivity(intent);
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM