简单的MP3播放器在模拟器上运行良好但不适用于实际设备

时间:2017-04-15 20:16:42

标签: android

所以我按照本教程关于如何创建一个简单的音乐播放器并在genymotion上运行得很好,现在我想在我的手机上运行它但它从一开始就崩溃了,这是我的代码

package com.bignerdranch.android.musicplayer;

import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; 
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import java.io.IOException;
import java.math.BigDecimal;

public class MainActivity extends ListActivity {

private static final int UPDATE_FREQUENCY=500;
private static final int STEP_VALUE=4000;

private MediaCursorAdapter mediaAdapter=null;
private TextView selectedfile=null;
private SeekBar seekbar=null;
private MediaPlayer player=null;
private ImageButton PlayButton=null;
private ImageButton PrevButton=null;
private ImageButton NextButton=null;

private boolean isStarted=true;
private String currentFile="";
private boolean isMovingSeekBar=false;

private final Handler handler=new Handler();

private final Runnable updatepostionRunnable=new Runnable() {
    public void run() {
        updatePostion();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    selectedfile=(TextView) findViewById(R.id.selectedfile);
    seekbar=(SeekBar) findViewById(R.id.seekbar);
    PlayButton=(ImageButton)findViewById(R.id.play);
    PrevButton=(ImageButton)findViewById(R.id.prev);
    NextButton=(ImageButton)findViewById(R.id.next);

    player=new MediaPlayer();

    player.setOnCompletionListener(onCompletion);
    player.setOnErrorListener(onError);
    seekbar.setOnSeekBarChangeListener(seekBarChanged);

    Cursor cursor= 

getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null
,null,null);
    if (null !=cursor){
        cursor.moveToFirst();

        mediaAdapter= new MediaCursorAdapter(this, 
R.layout.listitem,cursor);

        setListAdapter(mediaAdapter);

        PlayButton.setOnClickListener(onButtonClick);
        NextButton.setOnClickListener(onButtonClick);
        PrevButton.setOnClickListener(onButtonClick);
    }
}

@Override
protected void onListItemClick(ListView list,View view,int position,long id)
{
    super.onListItemClick(list,view,position,id);

    currentFile=(String)view.getTag();

    startplay(currentFile);
}

@Override
public void onDestroy(){
    super.onDestroy();

    handler.removeCallbacks(updatepostionRunnable);
    player.stop();
    player.reset();
    player.release();

    player=null;
}

private void startplay(String file){
    Log.i("Selected ", file);
    selectedfile.setText(file);
    seekbar.setProgress(0);

    player.stop();
    player.reset();

    try{
        player.setDataSource(file);
        player.prepare();
        player.start();
    }catch (IllegalArgumentException e){
            e.printStackTrace();
    }catch (IllegalStateException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }
    seekbar.setMax(player.getDuration());

    PlayButton.setImageResource(android.R.drawable.ic_media_pause);
    updatePostion();
    isStarted=true;
}

private void stopplay(){
    player.stop();
    player.reset();
    PlayButton.setImageResource(android.R.drawable.ic_media_play);
    handler.removeCallbacks(updatepostionRunnable);
    seekbar.setProgress(0);

    isStarted=false;
}

private void updatePostion(){
    handler.removeCallbacks(updatepostionRunnable);

    seekbar.setProgress(player.getCurrentPosition());

    handler.postDelayed(updatepostionRunnable,UPDATE_FREQUENCY);
}

  private class MediaCursorAdapter extends SimpleCursorAdapter{

    public MediaCursorAdapter(Context context,int layout, Cursor c){
        super(context,layout,c,
                new String[]{MediaStore.MediaColumns.DISPLAY_NAME,
  MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
                new int[]{R.id.displayname,R.id.title,R.id.duration});
    }
    @Override
    public void bindView(View view, Context context,Cursor cursor){
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView name = (TextView) view.findViewById(R.id.displayname);
        TextView duration = (TextView) view.findViewById(R.id.duration);

        name.setText(cursor.getString(

cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));

        title.setText(cursor.getString(
                cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));

        long durationInMs=Long.parseLong(cursor.getString(

cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));

        double durationInMin = ((double) durationInMs /1000.0 ) / 60.0;
        durationInMin = new 

 BigDecimal(Double.toString(durationInMin)).setScale(
 2,BigDecimal.ROUND_UP).doubleValue();
        duration.setText("" + durationInMin);




view.setTag(cursor.getString(cursor.getColumnIndex
(MediaStore.MediaColumns.DATA)));
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent){
        LayoutInflater inflater= LayoutInflater.from(context);
        View v=inflater.inflate(R.layout.listitem,parent,false);
        bindView(v,context,cursor);
        return v;
    }
}
private View.OnClickListener onButtonClick=new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.play:{
                if(player.isPlaying()){
                    handler.removeCallbacks(updatepostionRunnable);
                    player.pause();

PlayButton.setImageResource(android.R.drawable.ic_media_play);
                }else{
                    if (isStarted){
                        player.start();

PlayButton.setImageResource(android.R.drawable.ic_media_pause);

                        updatePostion();
                    }else{
                        startplay(currentFile);
                    }
                }
                break;
            }
            case R.id.next:{
                int seekto=player.getCurrentPosition()+STEP_VALUE;

                if(seekto>player.getDuration()){
                    seekto=player.getDuration();
                }

                player.pause();
                player.seekTo(seekto);
                player.start();
                break;
            }
            case R.id.prev:{
                int seekto=player.getCurrentPosition()- STEP_VALUE;

                if (seekto<0){
                    seekto=0;
                }
                player.pause();
                player.seekTo(seekto);
                player.start();

                break;
            }
        }
    }
};

private MediaPlayer.OnCompletionListener onCompletion= new 
MediaPlayer.OnCompletionListener(){
  @Override
    public void onCompletion(MediaPlayer mp){
      stopplay();
  }
};

private  MediaPlayer.OnErrorListener onError=new 
MediaPlayer.OnErrorListener(){
    @Override
    public boolean onError(MediaPlayer mp,int what, int extra){
    return false;
    }
};

private SeekBar.OnSeekBarChangeListener seekBarChanged = new 
SeekBar.OnSeekBarChangeListener(){
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean 
fromUser) {
        if (isMovingSeekBar){
            player.seekTo(progress);
            Log.i("OnSeekBarChangeListener","onProgressChanged");
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isMovingSeekBar=true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        isMovingSeekBar=false;
    }

};



}

这里是显示器错误的事情

    04-16 20:25:40.009 2516-2516/? I/SELinux: Function: selinux_android_load_priority [0], There is no sepolicy file.

04-16 20:25:40.039 2516-2516/? I/SELinux: Function: selinux_android_load_priority , spota verifySig and checkHash pass. priority version is VE=SEPF_GT-I9515_4.4.2_0040


04-16 20:25:40.039 2516-2516/? I/SELinux: selinux_android_seapp_context_reload: seapp_contexts file is loaded from /data/security/spota/seapp_contexts
04-16 20:25:40.039 2516-2516/? E/dalvikvm: >>>>> Normal User
04-16 20:25:40.039 2516-2516/? E/dalvikvm: >>>>> com.bignerdranch.android.musicplayer [ userId:0 | appId:10200 ]
04-16 20:25:40.039 2516-2516/? D/dalvikvm: Late-enabling CheckJNI
04-16 20:25:40.139 2516-2516/com.bignerdranch.android.musicplayer I/InstantRun: Instant Run Runtime started. Android package is com.bignerdranch.android.musicplayer, real application class is null.
04-16 20:25:40.149 2516-2516/com.bignerdranch.android.musicplayer W/InstantRun: No instant run dex files added to classpath
04-16 20:25:40.169 2516-2516/com.bignerdranch.android.musicplayer W/ApplicationPackageManager: getCSCPackageItemText()
04-16 20:25:40.169 2516-2516/com.bignerdranch.android.musicplayer I/PersonaManager: getPersonaService() name persona_policy
04-16 20:25:40.219 2516-2516/com.bignerdranch.android.musicplayer D/AbsListView: Get MotionRecognitionManager
04-16 20:25:40.239 2516-2516/com.bignerdranch.android.musicplayer D/ProgressBar: setProgressDrawable drawableHeight = 36
04-16 20:25:40.249 2516-2516/com.bignerdranch.android.musicplayer D/AbsSeekBar: AbsSeekBar Constructor: misSeebarAnimationAvailable = true
04-16 20:25:40.259 2516-2516/com.bignerdranch.android.musicplayer V/MediaPlayer-JNI: native_setup
04-16 20:25:40.259 2516-2516/com.bignerdranch.android.musicplayer V/MediaPlayer: constructor
04-16 20:25:40.259 2516-2516/com.bignerdranch.android.musicplayer V/MediaPlayer: setListener
04-16 20:25:40.319 2516-2516/com.bignerdranch.android.musicplayer D/AbsListView: onVisibilityChanged() is called, visibility : 4
04-16 20:25:40.319 2516-2516/com.bignerdranch.android.musicplayer D/AbsListView: unregisterIRListener() is called 
04-16 20:25:40.339 2516-2516/com.bignerdranch.android.musicplayer D/AbsListView: onVisibilityChanged() is called, visibility : 0
04-16 20:25:40.339 2516-2516/com.bignerdranch.android.musicplayer D/AbsListView: unregisterIRListener() is called 
04-16 20:25:40.339 2516-2516/com.bignerdranch.android.musicplayer D/AbsListView: unregisterIRListener() is called 
04-16 20:25:40.359 2516-2516/com.bignerdranch.android.musicplayer D/AndroidRuntime: Shutting down VM
04-16 20:25:40.359 2516-2516/com.bignerdranch.android.musicplayer W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x420c3da0)
04-16 20:25:40.370 2516-2516/com.bignerdranch.android.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: com.bignerdranch.android.musicplayer, PID: 2516
                                                                                    java.lang.NumberFormatException: Invalid long: "null"
                                                                                        at java.lang.Long.invalidLong(Long.java:124)
                                                                                        at java.lang.Long.parseLong(Long.java:341)
                                                                                        at java.lang.Long.parseLong(Long.java:318)
                                                                                        at com.bignerdranch.android.musicplayer.MainActivity$MediaCursorAdapter.bindView(MainActivity.java:164)
                                                                                        at android.widget.CursorAdapter.getView(CursorAdapter.java:254)
                                                                                        at android.widget.AbsListView.obtainView(AbsListView.java:2694)
                                                                                        at android.widget.ListView.measureHeightOfChildren(ListView.java:1274)
                                                                                        at android.widget.ListView.onMeasure(ListView.java:1186)
                                                                                        at android.view.View.measure(View.java:17387)
                                                                                        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
                                                                                        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
                                                                                        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                                        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                                        at android.view.View.measure(View.java:17387)
                                                                                        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
                                                                                        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                                        at android.view.View.measure(View.java:17387)
                                                                                        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
                                                                                        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
                                                                                        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                                        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                                        at android.view.View.measure(View.java:17387)
                                                                                        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
                                                                                        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                                        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2533)
                                                                                        at android.view.View.measure(View.java:17387)
                                                                                        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2215)
                                                                                        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1352)
                                                                                        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1551)
                                                                                        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1236)
                                                                                        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6473)
                                                                                        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
                                                                                        at android.view.Choreographer.doCallbacks(Choreographer.java:603)
                                                                                        at android.view.Choreographer.doFrame(Choreographer.java:573)
                                                                                        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
                                                                                        at android.os.Handler.handleCallback(Handler.java:733)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:157)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5356)
                                                                                        at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                        at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)

    at dalvik.system.NativeStart.main(Native Method)

请帮助,谢谢

1 个答案:

答案 0 :(得分:0)

这很可能是因为您拥有的仿真器和设备在两个不同的资源桶中使用了两个不同的XML布局文件。

https://developer.android.com/guide/practices/screens_support.html

您在适配器的bind方法中获得了一个空指针,因为它执行findViewById并且在提供的布局文件中找不到视图。然后返回null,如果您尝试在null上调用方法,则会导致崩溃。

解决方案:找到您使用的布局文件(listitem.xml),并在该res存储桶中更新它以获得您期望的视图,或删除它以使其回退到正确的xml文件(模拟器正在使用。)