Search code examples
javaandroidsortingalphabeticalandroid-music-player

Sorting alphabetically playlist of a music player (Android Studio)


I downloaded this project :

https://projectworlds.in/android-projects-with-source-code/android-music-player-project-with-source-code/

And I would sort alphabetically the songs in the "all songs" part. I tried to put this in onCreate :

Collections.sort(songList, Comparator.comparing((Function<? super Object, ? extends Comparable>) songList));

See the code here :

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AllSongFragment.createDataParse, FavSongFragment.createDataParsed, CurrentSongFragment.createDataParsed {

    private Menu menu;

    private ImageButton imgBtnPlayPause, imgbtnReplay, imgBtnPrev, imgBtnNext, imgBtnSetting;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private SeekBar seekbarController;
    private DrawerLayout mDrawerLayout;
    private TextView tvCurrentTime, tvTotalTime;


    private ArrayList<SongsList> songList;
    private int currentPosition;
    private String searchText = "";
    private SongsList currSong;

    private boolean checkFlag = false, repeatFlag = false, playContinueFlag = false, favFlag = true, playlistFlag = false;
    private final int MY_PERMISSION_REQUEST = 100;
    private int allSongLength;
    MediaPlayer mediaPlayer;
    Handler handler;
    Runnable runnable;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        grantedPermission();
        onPrepared();
        //Sorting playlist here
        Collections.sort(songList, Comparator.comparing((Function<? super Object, ? extends Comparable>) songList));

    }

but the app crashes. The arraylist doesn't have objects so I cannot use toCompare (ex: obj 1 and obj 2). I want to compare the ArrayList itself>

Any ideas about that ? Thanks in advance.

SongList.java :

package com.example.soc_macmini_15.musicplayer.Model;
public class SongsList {

    private String title;
    private String subTitle;
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public SongsList(String title, String subTitle, String path) {
        this.title = title;
        this.subTitle = subTitle;
        this.path = path;

    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubTitle() {
        return subTitle;
    }

}

Solution

  • The Function in Comparator.comparing should be provided as a method reference:

    Collections.sort(songList, Comparator.comparing(SongList::getTitle));