尝试在我的musicapp中的空对象引用上调用虚方法'android.content.Context android.content.Context.getApplicationContext()'

时间:2017-06-29 12:03:42

标签: java android nullpointerexception

我正在尝试创建一个简单的音乐应用程序,但是当我点击歌曲名称时,应用程序会崩溃,并且会抛出异常。

'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 个答案:

答案 0 :(得分:2)

您无法通过创建新对象来启动服务: 你在做什么:

 //               PIC S9(03)  COMP-3.

protected static PackedDecimalAsBigDecimalField epcutb_org = factory.getPackedDecimalAsBigDecimalField(3, 0, true);

 //               PIC S9(03)  COMP-3.

protected static PackedDecimalAsBigDecimalField epcutb_curr = factory.getPackedDecimalAsBigDecimalField(3, 0, true);

//               PIC S9(06)  COMP-3.

protected static PackedDecimalAsBigDecimalField epcutb_org_curr = factory.getPackedDecimalAsBigDecimalField(6, 0, true);

public void setEpcutb_org(BigDecimal utb_org) { //utb_org==867

epcutb_org.putBigDecimal(utb_org ,epcutbytes);

 }

public void setEpcutb_curr(BigDecimal utb_curr) { // utb_curr=840

epcutb_curr.putBigDecimal(utb_curr ,epcutbytes);

 }


public BigDecimal getEpcutb_org_curr() { 

epcutb_org_curr.setOffset(epcutb_org.getOffset());  // here concatenation is happening for epcutb_org and epcutb_curr so the return value should be "867840" but the return value i am getting is "8682840"

return epcutb_org_curr.getBigDecimal(epcutbytes);
 }

并且在playSong方法中,您尝试使用getApplicationContext(),它将为null,因为您需要启动服务而不是创建它的对象,如:

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