2017-06-29 45 views
-1

私は単純なミュージックアプリケーションを作ろうとしていますが、アプリがクラッシュし、例外がスローされます。私のmusicappのヌルオブジェクト参照で、仮想メソッド 'android.content.Context android.content.Context.Context.getApplicationContext()'を呼び出そうとしています

'Attempt to invoke virtual method Error setting data source java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object referenceat android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:117) at com.studios.debug.musicplayer.MusicService.playSong(MusicService.java:87) at com.studios.debug.musicplayer.RecyclerViewAdapter$MyViewHolder$1.onClick(RecyclerViewAdapter.java:58) at android.view.View.performClick(View.java:5207) at android.view.View$PerformClick.run(View.java:21177) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5438) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 06-29 17:40:48.070 20284-20284/com.studios.debug.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main Process: com.studios.debug.musicplayer, PID: 20284 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.prepareAsync()' on a null object reference at com.studios.debug.musicplayer.MusicService.playSong(MusicService.java:91) at com.studios.debug.musicplayer.RecyclerViewAdapter$MyViewHolder$1.onClick(RecyclerViewAdapter.java:58) at android.view.View.performClick(View.java:5207) at android.view.View$PerformClick.run(View.java:21177) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5438) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) on a null object reference' ここ

が私のコードです: MusicService.java

public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { 
private final IBinder musicBind = new MusicBinder(); 
private MediaPlayer player; 
private ArrayList<Song> songs; 
private int songposition; 

@Override 
public void onCreate() { 
    super.onCreate(); 
    songposition = 0; 
    player = new MediaPlayer(); 
    initMusicPlayer(); 
} 

public void initMusicPlayer() { 
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); 
    player.setAudioStreamType(AudioManager.STREAM_MUSIC); 
    player.setOnPreparedListener(this); 
    player.setOnCompletionListener(this); 
    player.setOnErrorListener(this); 

} 

public void setList(ArrayList<Song> theSong) { 
    Log.e("Test", "" + theSong.size()); 
    this.songs = theSong; 
} 

@Override 
public boolean onUnbind(Intent intent) { 

    return false; 

} 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return musicBind; 
} 

@Override 
public void onCompletion(MediaPlayer mp) { 

} 

@Override 
public boolean onError(MediaPlayer mp, int what, int extra) { 
    /* mp.reset();*/ 
    return false; 
} 

@Override 
public void onPrepared(MediaPlayer mp) { 
    mp.start(); 

} 

public void playSong(ArrayList<Song> songs1) { 
    Log.e("Test1", "" + songs1.size()); 

    Song playSong = songs1.get(songposition); 
    long currSong = playSong.getID(); 
    Uri trackUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong); 
    try { 
     player.setDataSource(getApplicationContext(), trackUri); 
    } catch (Exception e) { 
     Log.e("MUSIC SERVICE", "Error setting data source", e); 
    } 
    player.prepareAsync(); 
} 

public void setSong(int songIndex) { 
    songposition = songIndex; 
} 

public class MusicBinder extends Binder { 
    MusicService getService() { 
     return MusicService.this; 
    } 
} 
} 

MainActivity.java

public class MainActivity extends AppCompatActivity { 
    private ArrayList<Song> songArrayList; 
    private RecyclerView recyclerView; 
    private RecyclerViewAdapter recyclerViewAdapter; 
    private MusicService musicSrv; 
    private Intent playIntent; 
    private MediaPlayer player; 
    private boolean musicBound = false; 
    private ServiceConnection musicConnection = new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      MusicBinder binder = (MusicBinder) service; 
      musicSrv = binder.getService(); 
      musicSrv.setList(songArrayList); 
      musicBound = true; 
     } 

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

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

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
       requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); 
       return; 
      } 
     } 
     recyclerView = (RecyclerView) findViewById(R.id.songs_lists); 
     songArrayList = new ArrayList<Song>(); 


     getSongList(); 
     Collections.sort(songArrayList, new Comparator<Song>() { 
      @Override 
      public int compare(Song o1, Song o2) { 
       return o1.getTitle().compareTo(o2.getTitle()); 
      } 
     }); 
     recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this, songArrayList); 
     RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); 
     recyclerView.setLayoutManager(mLayoutManager); 
     recyclerView.addItemDecoration(new SimpleDivider(MainActivity.this)); 
     recyclerView.setAdapter(recyclerViewAdapter); 

    } 

    public void getSongList() { 
     ContentResolver contentResolver = getContentResolver(); 
     Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
     Cursor musicCursor = contentResolver.query(musicUri, null, null, null, null); 
     Log.e("test",""+musicCursor.getCount()); 
     if (musicCursor != null && musicCursor.moveToFirst()) { 
      do { 
       long thisId = musicCursor.getLong(musicCursor.getColumnIndex(MediaStore.Audio.Media._ID)); 
       String thisTitle = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE)); 
       String thisArtist = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)); 

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

     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.main, menu); 
     return true; 


    } 

    @Override 
    protected void onDestroy() { 
     if (musicBound) unbindService(musicConnection); 
     stopService(playIntent); 
     musicSrv = null; 
     /* player.stop(); 
     player.release();*/ 
     super.onDestroy(); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case R.id.action_shuffle: 
       break; 
      case R.id.action_end: 
       stopService(playIntent); 
       musicSrv = null; 
       System.exit(0); 
       break; 
     } 
     return super.onOptionsItemSelected(item); 
    } 



} 

RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> { 
     Context context; 
     private ArrayList<Song> songs; 
     private MusicService musicSrv; 

     public RecyclerViewAdapter(Context c, ArrayList<Song> songs1) { 
      this.songs = songs1; 
      Log.e("Test", "" + songs.size()); 
      this.context = c; 
     } 

     @Override 
     public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
      View view = LayoutInflater.from(context).inflate(R.layout.row_list, parent, false); 
      return new MyViewHolder(view); 
     } 

     @Override 
     public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, int position) { 
      Song song = songs.get(position); 
      holder.title.setText(song.getTitle()); 
      holder.artist.setText(song.getArtist()); 
     } 

     @Override 
     public int getItemCount() { 
      return songs.size(); 
     } 

     public class MyViewHolder extends RecyclerView.ViewHolder { 
      public TextView title, artist; 

      public MyViewHolder(View itemView) { 
       super(itemView); 
       title = (TextView) itemView.findViewById(R.id.song_title); 
       artist = (TextView) itemView.findViewById(R.id.song_artist); 
       itemView.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         musicSrv=new MusicService(); 
         musicSrv.setSong(getLayoutPosition()); 
         musicSrv.playSong(songs); 
        } 
       }); 
      } 
     } 
    } 
+1

これらのいずれの場合でも 'getApplicationContext()'は必要ありません。 「これ」はうまくいくか良くなるだろう。それ以外に、あなたの質問を編集し、あなたの例外に関連するJavaスタックトレース全体を投稿してください。 – CommonsWare

答えて

2

あなたは、新しいオブジェクトを作成することでサービスを開始することはできません。何をやっている は次のとおりです。

musicSrv=new MusicService(); 
         musicSrv.setSong(getLayoutPosition()); 
         musicSrv.playSong(songs); 

とplaySong方法であなたがあなたの代わりにサービスを開始する必要があるとして、nullになるgetApplicationContext()を使用しようとしています

Intent intent = new Intent(context, MusicService.class); 
     context.startService(intent); 
+0

どこで私はstartServiceを正確に持っていますか? –

+0

MusicServiceの新しいオブジェクトを作成するRecyclerViewAdapter.javaクラス – Piyush

関連する問題