Android onSaveInstanceState和/或onRestoreInstanceState崩溃

时间:2013-11-01 21:43:47

标签: android

我对Android的编程比较陌生,我陷入了(可能是简单的)问题。我已经尝试了几个小时搞乱但却无处可寻......

我的代码如下,它会在旋转设备并重新启动活动时停止应用程序。我使用了onSaveInstanceState和onRestoreInstanceState方法,但他们没有帮助我!有人可以看一下:

public class DebugActivity extends Activity implements GPSCallback{
private GPSManager gpsM=null;
private ConvertSpeed conS =null;
private double speed = 0.0;

    @Override
    public void onCreate(Bundle savedInstanceState){
        if(savedInstanceState != null){
            speed = savedInstanceState.getDouble("speed");
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debug);
        gpsM = new GPSManager();
        gpsM.startListening(getApplicationContext());
        gpsM.setGPSCallback(this);
        conS = new ConvertSpeed();
    }
    @Override
    public void onSaveInstanceState(Bundle outState){
        outState.putDouble("speed",speed);
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        speed = savedInstanceState.getDouble("speed");
    }
@Override
    public void onDestroy(){
        gpsM.stopListening();
        gpsM.setGPSCallback(null);
        gpsM = null;
    }
    @Override
    public void onGPSUpdate(Location location) {
        location.getLatitude();
        location.getLongitude();
        speed = location.getSpeed();
        String speedString = "" + conS.convertSpeed(speed,2);
        TextView debug1 = ((TextView)findViewById(R.id.tvSpeed));
        debug1.setText(speedString);
    }
}

调试:

onCreate方法中,第一次活动运行:

if(savedInstanceState != null){
speed = savedInstanceState.getDouble("speed");

它显示outState = nullspeed = 0.0

屏幕旋转,onSaveInstanceState方法显示outState = Bundle[{speed=0.0}],然后2秒后崩溃而没有再次到达onRestoreInstanceStateonCreate

2 个答案:

答案 0 :(得分:0)

将此onCreate替换为

@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debug);

        if(savedInstanceState != null){
            speed = savedInstanceState.getDouble("speed");
        }

        gpsM = new GPSManager();
        gpsM.startListening(getApplicationContext());
        gpsM.setGPSCallback(this);
        conS = new ConvertSpeed();
    }

onSaveInstanceState

 @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putDouble("speed",speed);
    }

删除此onRestoreInstanceState

 @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        speed = savedInstanceState.getDouble("speed");
    }

在你这样做之后它应该可以正常工作

答案 1 :(得分:0)

我有更深入地了解调试日志(显然是在3075 google搜索之后......),错误似乎是我没有调用super.onDestroy()!它现在似乎工作!!