2011-03-18 2 views
0

J'ai un service multimédia personnalisé et une classe de lecteur audio qui communique avec elle mais n'est pas liée au service.Impossible d'obtenir la durée de la chanson dans onCreate, mais peut l'obtenir en appuyant sur le bouton

Lorsque je crée un objet de MyService et d'écrire le code: - myService.player.getDuration() dans onCreate je reçois l'exception de pointeur nul sur cette ligne.

Mais si j'écris ce code en cliquant sur un bouton de l'écouteur sur le même écran, alors j'obtiens la durée exacte.

J'ai essayé toutes les syntaxes possibles pour résoudre cela, mais je ne suis toujours pas capable de résoudre le problème.

** Le code de mon service est: - **

private static final String TAG = "MyService"; 
    public static MediaPlayer player; 
    String song_uri,url; 
    Bundle b; 
    private IBinder myBinder; 
    private boolean isplaying; 
    public static final String Song_uri="song_uri"; 
    public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE"; 

     @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 
    public class MyBinder extends Binder{ 
     MyService getService() 
     { 
      return MyService.this; 
     } 
    } 

    @Override 
    public void onCreate() { 
     Log.d(TAG, "onCreate "+song_uri); 
      } 


    @Override 
    public void onDestroy() { 
     //Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show(); 
     DataManager.getInstance().setWantsToPlaySong(false); 
     DataManager.getInstance().setCurrentPosition(0); 
     Log.d(TAG, "onDestroy"); 
     player.stop(); 
    //player.release(); 
    } 

public void onPause() 
{ 

player.pause(); 
} 

public double duration() 
{ 
return player.getDuration();  
} 

    public void onStart(Intent intent, int startid) { 
     DataManager.getInstance().setWantsToPlaySong(true); 
    Bundle b=intent.getExtras(); 
    song_uri=b.getString("song_uri"); 
    Uri path=Uri.parse(song_uri); 


    player = MediaPlayer.create(this,path); 
    player.setLooping(false); // Set looping 
    //Toast.makeText(this, "My Service Started"+" Duration = "+(player.getDuration()/1000)/60, Toast.LENGTH_SHORT).show(); 
     Log.d(TAG, "onStart"+song_uri); 
     player.start(); 
    } 

Le code du lecteur audio est: -

uri = this.getIntent().getExtras().getString("song_uri"); 
     buttonStart = (Button) findViewById(R.id.buttonStart); 
     buttonStop = (Button) findViewById(R.id.buttonStop); 
     buttonPause = (Button) findViewById(R.id.buttonPause); 
     tracks = dbManager.getAllSongs(AudioPlayer2.this); 

     buttonForward = (Button) findViewById(R.id.buttonforward); 
     buttonBackward = (Button) findViewById(R.id.buttonbackward); 
     //========================================================================================= 
     sArtworkUri = Uri.parse("content://media/external/audio/albumart"); 
      //myservice=new MyService(); 

     Uri path = Uri.parse(uri); 
     current_song=this.getIntent().getExtras().getInt("current_song"); 
     albumArtUri = this.getIntent().getExtras().getString("album_art"); 
     Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart"); 
     album_id = Long.parseLong(this.getIntent().getStringExtra("album_id")); 
     int id = Integer.parseInt(this.getIntent().getStringExtra("album_id")); 

     albumImageUri = ContentUris.withAppendedId(sArtworkUri, album_id); 
     ivAlbumArt = (ImageView) findViewById(R.id.album_art); 

     songName = this.getIntent().getStringExtra("song_name"); 
     albumName = this.getIntent().getStringExtra("album_name"); 

     tvName = (TextView) findViewById(R.id.tv_name); 
     tvAlbum = (TextView) findViewById(R.id.tv_album); 
     if (songName != null) { 
      tvName.setText(songName); 
     } 

     if (albumName != null) { 
      tvAlbum.setText(albumName); 
     } 

    // buttonStart.performClick(); 

     if (DataManager.getInstance().getOnPausedSong()=="y"){ 
      //Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show(); 
      if(DataManager.getInstance().getPausedSongName()==songName){ 
       //Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show(); 
      buttonStart.setVisibility(View.GONE); 
      buttonPause.setVisibility(View.VISIBLE); 
     } 
     } 
     FetchImage fetchImage = new FetchImage(); 
     fetchImage.execute(); 

      /*if(DataManager.getInstance().getSong_uri()!=null) 
      { 
       stopService(new Intent(this, MyService.class)); 
      }*/ 
    // if(myService.player.isPlaying()) 
     //{ 
     stopService(new Intent(this, MyService.class)); 
     Intent intent = new Intent(this,MyService.class); 
      Bundle b = new Bundle(); 
      b.putString("song_uri",uri); 
      intent.putExtras(b); 
      startService(intent); 
      myService.player.setOnCompletionListener(new OnCompletionListener() { 

       @Override 
       public void onCompletion(MediaPlayer mp) { 
        // TODO Auto-generated method stub 
        buttonStart.setVisibility(View.VISIBLE); 
        buttonPause.setVisibility(View.GONE); 
       } 
      }); 
      buttonStart.setVisibility(View.GONE); 
      buttonPause.setVisibility(View.VISIBLE); 

      // Toast.makeText(this, "Duration: "+myService.player.getDuration(), Toast.LENGTH_LONG).show(); 
     /*//}//DataManager.getInstance().setSong_uri(uri); 
     Intent intent = new Intent(this,MyService.class); 
     Bundle b = new Bundle(); 
     b.putString("song_uri",uri); 
     intent.putExtras(b); 
     startService(intent); 
     buttonStart.setVisibility(View.GONE); 
     buttonPause.setVisibility(View.VISIBLE); 
     DataManager.getInstance().setSong_uri(uri); 
     DataManager.getInstance().setOnPausedSong("y"); 
     DataManager.getInstance().setPausedSongName(songName); 
     */ //buttonStart.setPressed(true); 

     //======================================================================================= 
     buttonStart.setOnClickListener(this); 
     buttonPause.setOnClickListener(this); 
     buttonForward.setOnClickListener(this); 
     buttonBackward.setOnClickListener(this); 
     buttonStop.setOnClickListener(this); 
     // buttonPause.performClick(); 
/*  new Thread(myThread).start(); 

*/ } 

     // Thread for seekbar 


     // song starts playing 

     public void onClick(View src) { 
     switch (src.getId()) { 
     case R.id.buttonStart: 
      if(DataManager.getInstance().getSongPause()=="y"){ 
       myService.player.start(); 
       DataManager.getInstance().setSongPause("n"); 
       buttonStart.setVisibility(View.GONE); 
       buttonPause.setVisibility(View.VISIBLE); 
      // DataManager.getInstance().setWantsToPlaySong(true); 
       //DataManager.getInstance().setOnPausedSong("n"); 
       //DataManager.getInstance().setOnPausedSong("y"); 
      }else{ 
     stopService(new Intent(this, MyService.class)); 
      DataManager.getInstance().setSong_uri(uri); 
      Intent intent = new Intent(this,MyService.class); 
      Bundle b = new Bundle(); 
      b.putString("song_uri",uri); 
      intent.putExtras(b); 
      startService(intent); 
      buttonStart.setVisibility(View.GONE); 
      buttonPause.setVisibility(View.VISIBLE); 
      DataManager.getInstance().setOnPausedSong("y"); 
      DataManager.getInstance().setPausedSongName(songName); 
      } 
      //Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
      break; 
     case R.id.buttonStop: 
      Log.d(TAG, "onClick: stopping srvice"); 
      stopService(new Intent(this, MyService.class)); 
      buttonStart.setVisibility(View.VISIBLE); 
      buttonPause.setVisibility(View.GONE); 
    break; 
     case R.id.buttonforward: 
      stopService(new Intent(this, MyService.class)); 
      current_song++; 
      FetchAllMusic fetchAllMusic = new FetchAllMusic(); 
      fetchAllMusic.execute(); 
      //new Thread(myThread).start(); 


       break; 
     case R.id.buttonbackward: 
       Log.d(TAG, "onClick: stopping service"); 
       stopService(new Intent(this, MyService.class)); 
       if(current_song>0){ 
       current_song--; 
       } 
       FetchAllMusic fetchAllMusic2 = new FetchAllMusic(); 
       fetchAllMusic2.execute(); 

       break; 
     case R.id.buttonPause: 
       buttonStart.setVisibility(View.VISIBLE); 
       buttonPause.setVisibility(View.GONE); 
      /* MyService myservice=new MyService(); 
      myservice.onPause();*/ 
       myService.player.pause(); 
       DataManager.getInstance().setSongPause("y"); 
       DataManager.getInstance().setWantsToPlaySong(false); 
       DataManager.getInstance().setOnPausedSong("n"); 
       DataManager.getInstance().setPausedSongName(songName); 
       //duration=myService.player.getDuration(); 

      // Toast.makeText(this, ""+duration, Toast.LENGTH_LONG).show(); 

     } 
     } 
     public void onBackPressed() { 
      try { 
        //addvideo.removeView(DBManager.getInstance().getVideo()); 
       DataManager.getInstance().setSong_uri(uri); 
      DataManager.getInstance().setAlbum_id(""+album_id); 
      DataManager.getInstance().setAlbumName(albumName); 
      DataManager.getInstance().setSongName(songName); 
      DataManager.getInstance().setAlbumArtUri(albumArtUri); 
      DataManager.getInstance().setCurrent_song(current_song); 
      DataManager.getInstance().setWantsToPlaySong(false); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      super.onBackPressed(); 
     } 

      private Runnable myThread = new Runnable(){ 

       @Override 
       public void run() { 
         Log.d(TAG, "Thread Starts"); 
       // TODO Auto-generated method stub 
       while (myProgress<100){ 
       try{ 
         Log.d(TAG, "Thread Starts"); 
         myHandle.sendMessage(myHandle.obtainMessage()); 
       Thread.sleep(3000); 
       } 
       catch(Throwable t){ 
       } 
       } 
       } 

       Handler myHandle = new Handler(){ 

       public void handleMessage(Message msg) { 
       // TODO Auto-generated method stub 
       myProgress++; 
       seekbar.setProgress(myProgress); 
       } 
       }; 
       }; 

Répondre

2

Ce n'est pas un problème de syntaxe; c'est un problème d'initialisation variable. myService ou myService.player est null lorsque cette ligne s'exécute en onCreate(). Vérifiez votre code pour l'endroit où vous les initialisez et assurez-vous de ne pas les référencer avant qu'ils ne soient définis.

+0

où dois-je initialiser en code? J'ai fait peut-être tout ce que j'ai même initialisé dans mon baseScreen que chaque activité dans mon application s'étend à. myService.player ne peut pas être nul car le morceau est en cours de lecture et myService ne peut pas être nul puisqu'il s'agit de la variable initialisée dans la classe baseScreen – abhishek

+0

maintenant j'ai écrit ce morceau de code myService = new MyService(); \t Toast.makeText (AudioPlayer2.this, "" + monService.player.getDuration(), Toast.LENGTH_SHORT) .show(); et même cela me donne l'exception nullPointer ... S'il vous plaît aider – abhishek

+0

Est-ce que le constructeur 'MyService()' attribue une valeur à 'player'? Si non, c'est votre problème. (Si, comme vous le dites, le code fonctionne dans un écouteur onClick, je soupçonne que 'player' est assigné un peu plus tard dans l'exécution de votre code.) –

Questions connexes