My Base Adapter, List<Song> songlist has a size of 0, instead of 14. It's preventing me from using my imgCoverArt onClick

huangapple go评论64阅读模式
英文:

My Base Adapter, List<Song> songlist has a size of 0, instead of 14. It's preventing me from using my imgCoverArt onClick

问题

I have been trying to create a ListView with the PlaylistsAdapter. But whenever I try to click on imgCoverArt, the app crashes, stating that the songlist has a size of 0. I have tried changing the types of the variables and just changing the codes overall. But I just couldn't fix it and I don't know the issue.

Thanks in advance.

This was the error I got:

2020-08-10 03:52:56.720 3091-3091/sg.edu.tp.musicstream E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.musicstream, PID: 3091
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at sg.edu.tp.musicstream.PlaylistsAdapter$1.onClick(PlaylistsAdapter.java:88)
    at android.view.View.performClick(View.java:6294)
    at android.view.View$PerformClick.run(View.java:24770)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I have tried to include the relevant classes, and please let me know if you need anything else.

英文:

I have been trying to create a ListView with the PlaylistsAdapter. But whenever I try to click on imgCoverArt, the app crashes, stating that the songlist has a size of 0. I have tried changing the types of the variables and just changing the codes overall. But I just couldn't fix it and I don't know the issue.

Thanks in advance.

This was the error I got:

2020-08-10 03:52:56.720 3091-3091/sg.edu.tp.musicstream E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.musicstream, PID: 3091
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at sg.edu.tp.musicstream.PlaylistsAdapter$1.onClick(PlaylistsAdapter.java:88)
    at android.view.View.performClick(View.java:6294)
    at android.view.View$PerformClick.run(View.java:24770)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I have tried to include the relevant classes and please let me know if you need anything else.

package sg.edu.tp.musicstream;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;



import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import sg.edu.tp.musicstream.util.AppUtil;


public class PlaylistsAdapter extends BaseAdapter {

    Context mContext;
    LayoutInflater inflater;
    Song[] songs;
    List&lt;Song&gt; songlist;
    ArrayList&lt;Song&gt; arrayList;

    public PlaylistsAdapter(Context context, List&lt;Song&gt; songlist, Song[] songs)
    {
        mContext = context;
        inflater = LayoutInflater.from(mContext);
        this.songs = songs;
        this.songlist = songlist;
        this.arrayList = new ArrayList&lt;&gt;();
        this.arrayList.addAll(songlist);

    }

    public class ViewHolder
    {
        ImageButton imgCoverArt;
        TextView txtSongTitle;
        TextView txtArtist;
        ImageButton btnAddToPlaylist;
    }

    @Override
    public int getCount() {
        return songlist.size();
    }

    @Override
    public Object getItem(int position) {
        return songlist.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.playlist_listview, null);

            holder.imgCoverArt = convertView.findViewById(R.id.imgCoverArt);
            holder.txtSongTitle = convertView.findViewById(R.id.txtSongTitle);
            holder.txtArtist = convertView.findViewById(R.id.txtArtist);
            holder.btnAddToPlaylist = convertView.findViewById(R.id.btnAddToPlaylist);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.imgCoverArt.setImageResource(songlist.get(position).getCoverArt());
        holder.imgCoverArt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int index = 0; index &lt; songs.length; index++)
                {
                    if (songlist.get(position).getId().equals(songs[index].getId())) {
                        Song song = songs[index];
                        sendDataToActivity(songs, song);
                        AppUtil.popMessage(mContext, &quot;&quot;+ songlist.size());
                    }
                }
            }
        });

        holder.txtSongTitle.setText(songlist.get(position).getTitle());
        holder.txtArtist.setText(songlist.get(position).getArtist());

        if (position &gt;= 10) {
            holder.btnAddToPlaylist.setContentDescription(&quot;S10&quot; + position);
        } else {
            holder.btnAddToPlaylist.setContentDescription(&quot;S100&quot; + position);
        }

        return convertView;
    }


    public void sendDataToActivity(Song[] songs, Song song)
    {
        // 1. Create a new Intent and specify the source and destination screen/activity.
        Intent intent = new Intent(mContext, PlaySongActivity.class);

        songlist = HomeFragment.arrayList;
        songlist = new ArrayList&lt;&gt;();

        // 2. Store the song information into the Intent object to be sent over to the destination screen.
        intent.putExtra(&quot;id&quot;, song.getId());
        intent.putExtra(&quot;title&quot;, song.getTitle());
        intent.putExtra(&quot;artist&quot;, song.getArtist());
        intent.putExtra(&quot;fileLink&quot;, song.getFileLink());
        intent.putExtra(&quot;coverArt&quot;, song.getCoverArt());
        intent.putExtra(&quot;songs&quot;, songs);

        intent.putExtra(&quot;songlist&quot;, (Serializable) songlist);


        // 3. Launch the destination screen/activity
        mContext.startActivity(intent);
    }

    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        songlist.clear();
        if (charText.length()==0){
            songlist.addAll(arrayList);
        }
        else {
            for (Song song : arrayList){
                if (song.getTitle().toLowerCase(Locale.getDefault())
                        .contains(charText) || song.getArtist().toLowerCase(Locale.getDefault())
                        .contains(charText)){
                    songlist.add(song);
                }
            }
        }
        notifyDataSetChanged();
    }
package sg.edu.tp.musicstream;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;

import sg.edu.tp.musicstream.ui.main.SectionsPagerAdapter;
import sg.edu.tp.musicstream.util.AppUtil;

public class HomeActivity extends AppCompatActivity {

    private SectionsPagerAdapter sectionsPagerAdapter;
    
    private SongCollection songCollection = new SongCollection();

    static Song[] playlistSongs = new Song[14];

    static ArrayList&lt;Song&gt; playlist = new ArrayList&lt;&gt;();

    private Fragment homeFragment;
    private Fragment playlistsFragment;
    

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

        homeFragment = new HomeFragment();
        playlistsFragment = new PlaylistsFragment();

        sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        setUpViewPager(viewPager);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);


    }


    private void setUpViewPager(ViewPager viewPager) {
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        sectionsPagerAdapter.addFragment(homeFragment, &quot;Recommended Songs&quot;);
        sectionsPagerAdapter.addFragment(playlistsFragment, &quot;Playlist&quot;);
        viewPager.setAdapter(sectionsPagerAdapter);

    }

    public void addToPlaylist (View view) {
        String songId = view.getContentDescription().toString();
        Song song = songCollection.searchById(SongCollection.recommendedSongs, songId);
        playlist.add(song);
        AppUtil.popMessage(this, &quot;Added &quot; + song.getTitle() + &quot; to playlist!&quot;);

        playlistSongs[playlist.size()] = song;

        sectionsPagerAdapter.removeFragment(playlistsFragment, &quot;Playlist&quot;);
        sectionsPagerAdapter.addFragment(new PlaylistsFragment(), &quot;Playlist&quot;);

        ViewPager viewPager = findViewById(R.id.view_pager);
        setUpViewPager(viewPager);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);

    }


    public void removeAll(View view) {
        playlist.clear();
        PlaylistsFragment.songAdapter.notifyDataSetChanged();
    }


}
package sg.edu.tp.musicstream;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.text.TextUtils;
import android.view.MenuItem;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;

public class HomeFragment extends Fragment {

    private PlaylistsAdapter playlistsAdapter;

    private ListView listView;

    static ArrayList&lt;Song&gt; arrayList = new ArrayList&lt;&gt;();


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container,false);
        

        for (int index =0; index&lt;SongCollection.recommendedSongs.length; index++) {
            
            arrayList.add(SongCollection.recommendedSongs[index]);
        }

        listView = view.findViewById(R.id.listView);

        playlistsAdapter = new PlaylistsAdapter(getActivity(), arrayList, SongCollection.recommendedSongs);

        listView.setAdapter(playlistsAdapter);

        setHasOptionsMenu(true);

        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView)myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)){
                    playlistsAdapter.filter(&quot;&quot;);
                    listView.clearTextFilter();
                }
                else {
                    playlistsAdapter.filter(s);
                }
                return true;
            }
        });
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==R.id.settings){
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return true;
        }
        if (id==R.id.logOut){
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    
}
package sg.edu.tp.musicstream;

import java.util.List;
import java.util.Random;

public class SongCollection
{
    static Song[] recommendedSongs = new Song[14];
    private Song[] playlist1 = new Song[5];
    private Song[] playlist2 = new Song[5];

    public SongCollection()
    {
        //Recommended Songs
        Song photograph = new Song(&quot;S1000&quot;, &quot;Photograph&quot;, &quot;Ed Sheeran&quot;,&quot;097c7b735ceb410943cbd507a6e1dfda272fd8a8?cid=null&quot;,4.32, R.drawable.photograph);
        Song theWayYouLookTonight = new Song(&quot;S1001&quot;, &quot;The Way You Look Tonight&quot;, &quot;Michael Buble&quot;,&quot;a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null&quot;,4.39,R.drawable.michael_buble_collection);
        Song billieJean = new Song(&quot;S1002&quot;, &quot;Billie Jean&quot;, &quot;Michael Jackson&quot;,&quot;f504e6b8e037771318656394f532dede4f9bcaea?cid=2afe87a64b0042dabf51f37318616965&quot;,4.39,R.drawable.billie_jean);
        Song spark = new Song(&quot;S1003&quot;, &quot;Spark&quot;, &quot;TAEYEON&quot;,&quot;e857ae54599f2cca1703b598cef871664f36e72e?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.63, R.drawable.spark);
        Song darkside = new Song(&quot;S1004&quot;, &quot;Darkside&quot;, &quot;Alan Walker&quot;,&quot;2acc534ac733f8868c98e13e4f71917fae2e3ce3?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.53, R.drawable.darkside);
        Song diamondHeart = new Song(&quot;S1005&quot;, &quot;Diamond Heart&quot;, &quot;Alan Walker&quot;,&quot;d75c2b8e870acb087872bd49eeb5d6efb37cfc9d?cid=2afe87a64b0042dabf51f37318616965&quot;, 4.01, R.drawable.diamond_heart);
        Song ocean= new Song(&quot;S1006&quot;, &quot;Ocean (feat. Khalid)&quot;, &quot;Martin Garrix&quot;,&quot;5ce5ed5600e96f1604aff6b05c0dc35319023a1c?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.61, R.drawable.ocean);
        Song numb = new Song(&quot;S1007&quot;, &quot;Numb&quot;, &quot;Linkin Park&quot;,&quot;e6ccf7717f8a167bfea4afc1bf7da1a0cd707fbb?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.09, R.drawable.numb);
        Song sadForever = new Song(&quot;S1008&quot;, &quot;Sad Forever&quot;, &quot;Lauv&quot;,&quot;1250fb3bea03aee6da908ea67420ddd954ad812a?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.39, R.drawable.sad_forever);
        Song kyokiranbu = new Song(&quot;S1009&quot;, &quot;Kyokiranbu&quot;, &quot;GARNiDELiA&quot;,&quot;ec373ab20f18e1a4a7b19b3abaac3ce605690abd?cid=2afe87a64b0042dabf51f37318616965&quot;, 4.32, R.drawable.kyokiranbu);
        Song gokurakuJoudo= new Song(&quot;S1010&quot;, &quot;Gokuraku Joudo&quot;, &quot;GARNiDELiA&quot;,&quot;8924599ac778ebfbac7ddc2e5cc87961f82f736c?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.65, R.drawable.gokuraku_joudo);
        Song connect = new Song(&quot;S1011&quot;, &quot;Connect&quot;, &quot;ClariS&quot;,&quot;6692db454109aa077ed25e65df82a06d34017da6?cid=2afe87a64b0042dabf51f37318616965&quot;, 4.5, R.drawable.connect);
        Song wannabe = new Song(&quot;S1012&quot;, &quot;WANNABE&quot;, &quot;ITZY&quot;, &quot;2bae7f42bbae3cd75228d6400e37515b79467928?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.19, R.drawable.wannabe);
        Song icy = new Song(&quot;S1013&quot;, &quot;ICY&quot;, &quot;ITZY&quot;, &quot;118a0dea24f229f51ffff23a9d334cf5714dbaf6?cid=2afe87a64b0042dabf51f37318616965&quot;, 3.19, R.drawable.icy);

        recommendedSongs[0] = photograph;
        recommendedSongs[1] = theWayYouLookTonight;
        recommendedSongs[2] = billieJean;
        recommendedSongs[3] = spark;
        recommendedSongs[4] = darkside;
        recommendedSongs[5] = diamondHeart;
        recommendedSongs[6] = ocean;
        recommendedSongs[7] = numb;
        recommendedSongs[8] = sadForever;
        recommendedSongs[9] = kyokiranbu;
        recommendedSongs[10] = gokurakuJoudo;
        recommendedSongs[11] = connect;
        recommendedSongs[12] = wannabe;
        recommendedSongs[13] = icy;

 


    }

答案1

得分: 2

在你的适配器中,你有三种不同的存储歌曲的方式:

Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;

这是一个问题。选择一种类型,并在所有地方使用它。

适配器构建其逻辑围绕getCount()方法:

@Override
public int getCount() {
    return songlist.size();
}

它使用songlist。但是你的onClick()方法使用songs

@Override
public void onClick(View v) {
    for (int index = 0; index < songs.length; index++)
    // ...
}

如果你改为使用songlist,问题可能会消失。

英文:

In your adapter, you have three different ways of storing the songs:

> Song[] songs;
> List<Song> songlist;
> ArrayList<Song> arrayList;

This is a problem. Pick one type, and use it everywhere.

The adapter is building its logic around the getCount() method:

> @Override
> public int getCount() {
> return songlist.size();
> }

Which uses songlist. But your onClick() method uses songs:

> @Override
> public void onClick(View v) {
> for (int index = 0; index < songs.length; index++)
> // ...
> }

If you change this to use songlist instead, probably the issue will go away.

huangapple
  • 本文由 发表于 2020年8月10日 03:33:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63330550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定