使用SeekBar和MediaPlayer的java.lang.NullPointerException

时间:2014-06-04 02:18:29

标签: java android nullpointerexception android-mediaplayer seekbar

我是Android的新手,我试图在播放音频时运行搜索栏。

我收到错误"无法启动活动ComponentInfo:java.lang.NullPointerException"当我尝试使用" setMax"。

设置进度条的范围时

这是我的代码:

public class PlayerActivity extends Activity {
    private MediaPlayer mPlayer;
    private SeekBar mSeekBar;


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

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        initVariables();
    }

    public void initVariables(){
        mPlayer = new MediaPlayer();
        mPlayer = MediaPlayer.create(this, R.raw.raunchy);
        mPlayer.setOnCompletionListener(onCompletion);

        mSeekBar = (SeekBar) findViewById(R.id.seekBar1);
        mSeekBar.setMax(mPlayer.getDuration());
    }

    private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mPlayer) {
            mPlayer.release();
            Log.d("FINAL", "CORRECTO");
        }
    };

    public void playOrPause(View v) {
        if (!mPlayer.isPlaying()) {
            mPlayer.start();
        } else {
            mPlayer.pause();
        }
        mHandler.postDelayed(mRunnable, 100);
    }

    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mSeekBar.setMax(mPlayer.getDuration());
            if(mPlayer.isPlaying()){
                int mCurrentPosition = mPlayer.getCurrentPosition() / 1000;
                mSeekBar.setProgress(mCurrentPosition);
            }
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_player,
                    container, false);
            return rootView;
        }
    }

}

这是我的片段。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.jgutierrezgil.bmusic.MainActivity$PlaceholderFragment" >

<Button
    android:id="@+id/button_play"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="@string/play_button"
    android:onClick="playOrPause" />

<Button
    android:id="@+id/button_stop"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/button_play"
    android:text="@string/stop_button"
    android:onClick="stop" />

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toLeftOf="@+id/button_play"
    android:text="Button" />

<SeekBar
    android:id="@+id/seekBar1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button_play"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="14dp" />

<TextView
    android:id="@+id/startTimeField"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button1"
    android:layout_alignLeft="@+id/seekBar1"
    android:text="Small Text"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/endTimeField"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button_stop"
    android:layout_alignRight="@+id/seekBar1"
    android:text="Small Text"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<Button
    android:id="@+id/library"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/Player"
    android:layout_alignBottom="@+id/Player"
    android:layout_alignRight="@+id/seekBar1"
    android:layout_toRightOf="@+id/button_play"
    android:text="@string/library_button"
    android:onClick="toLibrary" />

<Button
    android:id="@+id/Player"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/seekBar1"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/button_play"
    android:clickable="false"
    android:focusable="false"
    android:longClickable="false"
    android:text="@string/player_button" />

这就是Logcat。

    06-03 22:04:47.023: E/AndroidRuntime(1191): FATAL EXCEPTION: main
06-03 22:04:47.023: E/AndroidRuntime(1191): Process: com.jgutierrezgil.bmusic, PID: 1191
06-03 22:04:47.023: E/AndroidRuntime(1191): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jgutierrezgil.bmusic/com.jgutierrezgil.bmusic.PlayerActivity}: java.lang.NullPointerException
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.os.Looper.loop(Looper.java:136)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at java.lang.reflect.Method.invokeNative(Native Method)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at java.lang.reflect.Method.invoke(Method.java:515)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at dalvik.system.NativeStart.main(Native Method)
06-03 22:04:47.023: E/AndroidRuntime(1191): Caused by: java.lang.NullPointerException
06-03 22:04:47.023: E/AndroidRuntime(1191):     at com.jgutierrezgil.bmusic.PlayerActivity.initVariables(PlayerActivity.java:41)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at com.jgutierrezgil.bmusic.PlayerActivity.onCreate(PlayerActivity.java:32)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.Activity.performCreate(Activity.java:5231)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-03 22:04:47.023: E/AndroidRuntime(1191):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-03 22:04:47.023: E/AndroidRuntime(1191):     ... 11 more
06-03 22:04:49.193: I/Process(1191): Sending signal. PID: 1191 SIG: 9

清单

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jgutierrezgil.bmusic"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jgutierrezgil.bmusic.PlayerActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您使用事务添加片段,然后您会立即尝试在视图层次结构中查找搜索栏视图。未找到seekbar,因此为null,因此在调用setMax时会出现NullPointerException。

您应该从PlayerActivity.onCreate()中删除这两行:

    mSeekBar = (SeekBar) findViewById(R.id.seekBar1);
    mSeekBar.setMax(mPlayer.getDuration());

并且在膨胀rootView之后将它们放在PlaceholderFragment.onCreateView()中,因此您知道将找到搜索条,如下所示:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_player,
                container, false);
        mSeekBar = (SeekBar) rootView.findViewById(R.id.seekBar1);
        mSeekBar.setMax(mPlayer.getDuration());
        return rootView;
    }