javaandroidandroid-intentandroid-arrayadaptercustom-arrayadapter

send data from ArrayAdapter to MainActivity withot renew MainActivity


i create a list of my song with CustomArrayAdapter and placed it into MainActivity .

MediaPlayer and SeekBar are in MainActivity .

i want to send music number from my CustomArrayAdapter to MainActivity and play it but when i use Intent , new MainActivity is creating again .

i want to send data to it without create Activity again .

how can i do this ???

thanks


Solution

  • If you use Intent and pass your data it will create new activity, what you can do is create an interface in your adapter as follows.

    public interface GetSongCallBack  { 
          void getSongNumber(int songNumber);
    }
    

    When you initialize your CustomAdapter in activity, pass an instance of this interface. Which will look like this :

    CustomAdapter adapter = new CustomAdapter(..., new CustomAdapter.GetSongCallBack() {
      public void getSongNumber(int songNumber) { 
      // do something here...
      }});
    

    Finally, whenever you want your activity to know that song has changed, call getSongNumber() this method. You can do it like this,

    In the CustomAdapters constructor you are getting instance of interface so,

    Declare a global variable :

    GetSongCallBack callback; 
    

    Also add this line in the constructor,

    public CustomAdapter(... ,GetSongCallBack callback) {
         .
         .
         this.callBack = callBack; 
      }
    

    And calling method goes like this,

    callBack.getSongNumber(song);