• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Why isn't mediacontroller shown?

I need to make a Controller for my player app. With the help of it user would play, pause, choose next or previous song. But this controller isn't shown and I don't know why?

I have already done method for setting data for controller and class for this controller.

Here's the code of the method:

Code:
private void setController(){
   controller = new MusicController(this);
   controller.setPrevNextListeners(new View.OnClickListener() {
       [USER=1021285]@override[/USER]
       public void onClick(View v) {
           playNext();
       }
   }, new View.OnClickListener() {
       [USER=1021285]@override[/USER]
       public void onClick(View v) {
           playPrev();
       }
   });
   controller.setMediaPlayer(this);
   controller.setAnchorView(findViewById(R.id.songList));
   controller.setEnabled(true);
}

And here's the code of the class:

Code:
package asus.example.com.player;

import android.content.Context;
import android.widget.MediaController;

public class MusicController extends MediaController {
   public MusicController(Context context) {
       super(context);
   }

   public void hide(){}
}`
 
Last edited by a moderator:
In the method, you haven't shown the controller, that's why it's invisible.
Can you check to see if writing below the controller.setEnabled(true); the controller.show(0); statement? It should be:
...
controller.setEnabled(true);
controller.show(0);
}
 
In the method, you haven't shown the controller, that's why it's invisible.
Can you check to see if writing below the controller.setEnabled(true); the controller.show(0); statement? It should be:

I added that line, but in such case I have error: Unable to add window -- token null is not valid; is your activity running?
 
show the stack trace.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: asus.example.com.player, PID: 5451
java.lang.RuntimeException: Unable to start activity ComponentInfo{asus.example.com.player/asus.example.com.player.ListOfSongsActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2581)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2647)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1502)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:683)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:319)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.widget.MediaController.show(MediaController.java:478)
at android.widget.MediaController.show(MediaController.java:427)
at asus.example.com.player.ListOfSongsActivity.setController(ListOfSongsActivity.java:225)
at asus.example.com.player.ListOfSongsActivity.onCreate(ListOfSongsActivity.java:62)
at android.app.Activity.performCreate(Activity.java:6270)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2647)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1502)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
 
You haven't shown enough code. What's happening here

Code:
at asus.example.com.player.ListOfSongsActivity.onCreate(ListOfSongsActivity.java:62)
 
You haven't shown enough code. What's happening here

Code:
at asus.example.com.player.ListOfSongsActivity.onCreate(ListOfSongsActivity.java:62)

Code:
package asus.example.com.player;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.MediaController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ListOfSongsActivity extends AppCompatActivity implements MediaController.MediaPlayerControl {

    private ArrayList<Song> songsList;
    private final String TAG = this.getClass().getSimpleName();
    private final String ARTIST = "ARTIST";
    private final String SONG = "SONG";

    private MyService musicService;
    private Intent playIntent;
    private boolean musicBounds = false;

    private MusicController controller;

    [USER=1021285]@override[/USER]
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_of_songs);
        ListView songsListView = findViewById(R.id.songList);
        songsList = new ArrayList<>();
        if (isStoragePermissionGranted()) {
            getSongsList();
        }
        Collections.sort(songsList, new Comparator<Song>() {
            [USER=1021285]@override[/USER]
            public int compare(Song o1, Song o2) {
                return o1.getTitle().compareTo(o2.getTitle());
            }
        });
        SongAdapter adapter = new SongAdapter(this, songsList);
        songsListView.setAdapter(adapter);
        songsListView.setOnItemClickListener(onClickListener);
        setController();
    }

    [USER=1021285]@override[/USER]
    protected void onStart() {
        super.onStart();
        if (playIntent==null){
            playIntent = new Intent(this, MyService.class);
            bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
            startService(playIntent);
        }
    }

    public void getSongsList(){
        ContentResolver musicResolver = getContentResolver();
        Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        @SuppressLint("Recycle")
        Cursor musicCursor = musicResolver.query(musicUri,null,null,null,null);
        if (musicCursor!=null && musicCursor.moveToFirst()){
            int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);

            do{
                long thisId = musicCursor.getLong(idColumn);
                String thisTitle = musicCursor.getString(titleColumn);
                String thisArtist = musicCursor.getString(artistColumn);

                songsList.add(new Song(thisId, thisTitle, thisArtist));
            }while (musicCursor.moveToNext());
        }
    }

    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG,"Permission is granted");
                return true;
            } else {

                Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else {
            Log.v(TAG,"Permission is granted");
            return true;
        }
    }

    private AdapterView.OnItemClickListener onClickListener = new AdapterView.OnItemClickListener(){
        [USER=1021285]@override[/USER]
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            songPicked(view);
//            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
//            intent.putExtra(ARTIST, songsList.get(position).getArtist());
//            intent.putExtra(SONG, songsList.get(position).getTitle());
//            startActivity(intent);
        }
    };

    private ServiceConnection musicConnection = new ServiceConnection() {
        [USER=1021285]@override[/USER]
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.MusicBinder binder = (MyService.MusicBinder) service;
            musicService = binder.getService();
            musicService.setList(songsList);
            musicBounds = true;
        }

        [USER=1021285]@override[/USER]
        public void onServiceDisconnected(ComponentName name) {
            musicBounds = false;
        }
    };

    public void songPicked(View view){
        musicService.setSong(Integer.parseInt(view.getTag().toString()));
        musicService.playSong();
    }

    [USER=1021285]@override[/USER]
    public void start() {
        musicService.go();
    }

    [USER=1021285]@override[/USER]
    public void pause() {
        musicService.pausePlayer();
    }

    [USER=1021285]@override[/USER]
    public int getDuration() {
        if (musicService!=null && musicService.isPlaying() && musicBounds){
            return musicService.getDur();
        }
        else {
            return 0;
        }
    }

    [USER=1021285]@override[/USER]
    public int getCurrentPosition() {
        return 0;
    }

    [USER=1021285]@override[/USER]
    public void seekTo(int pos) {
        musicService.seek(pos);
    }

    [USER=1021285]@override[/USER]
    public boolean isPlaying() {
        if (musicService!=null && musicBounds){
            return musicService.isPlaying();
        }
        else {
            return false;
        }
    }

    [USER=1021285]@override[/USER]
    public int getBufferPercentage() {
        return 0;
    }

    [USER=1021285]@override[/USER]
    public boolean canPause() {
        return true;
    }

    [USER=1021285]@override[/USER]
    public boolean canSeekBackward() {
        return true;
    }

    [USER=1021285]@override[/USER]
    public boolean canSeekForward() {
        return true;
    }

    [USER=1021285]@override[/USER]
    public int getAudioSessionId() {
        return 0;
    }

    private void setController(){
        controller = new MusicController(this);
        controller.setPrevNextListeners(new View.OnClickListener() {
            [USER=1021285]@override[/USER]
            public void onClick(View v) {
                playNext();
            }
        }, new View.OnClickListener() {
            [USER=1021285]@override[/USER]
            public void onClick(View v) {
                playPrev();
            }
        });
        controller.setMediaPlayer(this);
        controller.setAnchorView(findViewById(R.id.songList));
        controller.setEnabled(true);
        controller.show();
    }

    private void playNext(){
        musicService.playNext();
        controller.show(0);
    }

    private void playPrev(){
        musicService.playPrev();
        controller.show(0);
    }

}
[code]

Here's the code of the whole class
 
Last edited by a moderator:
You cannot call MediaController.show() at line 262 because the application has not finished initialising.

Try this pattern, use a listener class to initialise and show the MediaController. You may, or may not need to call show(). Try it.


Code:
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   String url = getIntent().getExtras().getString(Constants.URL);
   setContentView(R.layout.fragment_video_gallery);
   final VideoView videoView = (VideoView) findViewById(R.id.videoView);
   videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
       @Override
       public void onPrepared(MediaPlayer mp) {
           View progress = findViewById(R.id.videoProgress);
           progress.setVisibility(View.GONE);

           videoView.requestFocus();
           MediaController vidControl = new MediaController(VideoPlayerActivity.this);
           vidControl.setAnchorView(videoView);
           //vidControl.show();
           videoView.setMediaController(vidControl);
           videoView.start();
       }
   });
   videoView.setVideoURI(Uri.parse(url));
}


https://www.programcreek.com/java-api-examples/index.php?api=android.widget.MediaController
 
Back
Top Bottom