0

我收到此错误消息:

09-05 19:58:00.883: E/AndroidRuntime(21920): java.lang.RuntimeException: Unable to pause      activity {com.De7kat.Grid/com.De7kat.Grid.De7katGrid}: java.lang.NullPointerException

当我进入活动 2 并尝试通过单击设备上的后退按钮返回活动 1 时。

de7katgrid活动代码是:

package com.De7kat.Grid;


public class De7katGrid extends Activity {
private MediaPlayer mp;
public Integer[] mSongsIds = {
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,R.raw.far,
        R.raw.beet,    };
public Object getItem(int position) {
    return mSongsIds[position];
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_layout);

    GridView gridView = (GridView) findViewById(R.id.grid_view);

    // Instance of ImageAdapter Class
    gridView.setAdapter(new ImageAdapter(this));

    gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
             stopPlaying();
             mp = MediaPlayer.create(De7katGrid.this,mSongsIds[position]);
             mp.start();

           }
    });
}
@Override
public void onPause() {
    super.onPause();
    if (mp.isPlaying()) {
       mp.stop();



    }
}

    private void stopPlaying() {
        if (mp != null) {
            mp.stop();
            mp.release();
            mp = null;


       }
    }
 }
4

3 回答 3

0

你为什么不调用你的stopPlaying()方法onPause()?这比复制代码要好(并且您将摆脱NullPointerException,这是因为您不检查是否mp为空):

@Override
public void onPause() {
    super.onPause();
    stopPlaying();
}
于 2012-09-05T17:13:39.340 回答
0

我认为调用 onPause 时您的 mp 为空。

于 2012-09-05T17:14:12.337 回答
0

当您返回 Activity 时mpnull在您调用后,create()因为您未能释放前一个。像这样改变你的onPause()方法:

@Override
public void onPause() {
    super.onPause();
    stopPlaying();
}
于 2012-09-05T17:11:36.910 回答