当我从活动点回到主要时,应用程序会一直崩溃

时间:2012-09-05 17:04:36

标签: android

我收到此错误消息:

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;


       }
    }
 }

3 个答案:

答案 0 :(得分:0)

当您致电mp后,如果您未能发布上一个活动null,则返回create()活动onPause()。像这样更改@Override public void onPause() { super.onPause(); stopPlaying(); } 方法:

{{1}}

答案 1 :(得分:0)

为什么不在stopPlaying()中拨打onPause()方法?它比复制代码更好(你将摆脱NullPointerException,这是因为你不检查mp是否为空):

@Override
public void onPause() {
    super.onPause();
    stopPlaying();
}

答案 2 :(得分:0)

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