2016-07-01 6 views
0

私は音楽プレーヤーアプリを作っています。 SongsFragment.javaでリストアイテムをクリックすると、SongAnd.javaにインテントが送信されます。 musicSrvは常にnullです。私はgoogleでActivity lifecyleを探して、これと何か関係があると考えました。私は初心者なので、それを適用できませんでした。サービスオブジェクトが初期化されていない/呼び出されていないonServiceCreated

SongsFragment:PlayerActivity.javaで

@Override 
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    //musicSrv.setSong(position); 
    //musicSrv.playSong(); 
    Intent intent = new Intent(getContext(), PlayerActivity.class); 
    intent.putExtra("pos", position); 
    startActivity(intent); 
} 

public class PlayerActivity extends AppCompatActivity { 
private MusicService musicSrv; 
private Intent playIntent; 
private boolean musicBound=false; 
private static final String POS = "pos"; 
private int passedPos; 



protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    Bundle extras = getIntent().getExtras(); 
    passedPos = extras.getInt("pos",0); 
    musicSrv.setSong(passedPos); 
    musicSrv.playSong(); 

    setContentView(R.layout.activity_player); 
} 


ServiceConnection musicConnection = new ServiceConnection(){ 

    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
     MusicService.MusicBinder binder = (MusicService.MusicBinder)service; 
     //Get service 
     musicSrv = binder.getService(); 
     //Pass list 
     ArrayList<Song> songs = ((DataFetcher)getApplicationContext()).songList; 
     musicSrv.setList(songs); 
     musicBound = true; 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName name) { 
     musicBound = false; 
    } 
}; 

@Override 
public void onStart() { 
    super.onStart(); 
    if(playIntent==null) { 
     playIntent = new Intent(this,(Class)MusicService.class); 
     bindService(playIntent,musicConnection, Context.BIND_AUTO_CREATE); 
     startService(playIntent); 
    } 
} 

@Override 
public void onDestroy() { 
    stopService(playIntent); 
    musicSrv=null; 
    super.onDestroy(); 
} 

}

エラー:私はまず、onCreate()onStart()前に呼び出され、 "Attempt to invoke virtual method 'void services.MusicService.setSong(int)' on a null object reference"

答えて

1

を取得します。 bindService()がまだ呼び出されていないため、musicSrvnullになります。

第2に、bindService()自体は非同期です。あなたのonServiceConnected()メソッドが呼び出される前に、しばらく時間がかかります。

musicSrvは、そのフィールドに値を割り当てるまで使用できません。できるだけ早いうちにonServiceConnected()の内部まで行うことはできません。

musicSrvに関連するコールをonServiceConnected()またはそれ以降のイベントに移動するには、musicSrvを準備する必要があります。

また、bindService()に直接電話をしないでください。このアクティビティを使用して設定を変更すると問題が発生する可能性があります。 Applicationオブジェクト(例:getApplicationContext().bindService())を使用してbindService()(以降、unbindService())に電話してください。

+0

ありがとうございます!私はmusicSrv関連のステートメントをonServiceConnected()に移動しました。曲は再生されています。 –

関連する問題