下面的代码在某些设备上运行良好。但是在三星galaxy y duos和其他一些设备中,在拍照并单击保存时,再次调用应用程序对象oncreate和活动onCreate。这会导致存储在应用程序对象中的数据丢失。如何避免它
申请代码如下:
public class MyApplication extends Application {
int a = 0;
int b = 0;
int c = 0;
private static final String TAG = "MyApplication";
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "####MyApplication on Craetet called");
}
}
我的活动代码如下
public class MainActivity extends Activity {
private static final int SELECT_CAMERA = 1;
private static final String TAG = "MainActivity";
MyApplication app;
TextView tv1, tv2, tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
app = (MyApplication) getApplicationContext();
Log.i(TAG, "#### MainActivity onCreate called with values " + app.a + " " + app.b + " " + app.c);
Button b = (Button) findViewById(R.id.button1);
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
tv3 = (TextView) findViewById(R.id.textView3);
tv1.setText("" + app.a);
tv2.setText("" + app.b);
tv3.setText("" + app.c);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
app.a = 5;
app.b = 6;
app.c = 8;
Log.i(TAG, "after onclick values " + app.a + " " + app.b + " "+ app.c);
Intent intentPicture = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentPicture, SELECT_CAMERA);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_CAMERA) {
Log.i(TAG, "after image selected values " + app.a + " " + app.b
+ " " + app.c);
tv1.setText("" + app.a);
tv2.setText("" + app.b);
tv3.setText("" + app.c);
}
}
}
}
我的日志是
04-09 23:58:44.888: I/MyApplication(15189): ####MyApplication on Craetet called
04-09 23:58:45.160: I/MainActivity(15189): #### MainActivity onCreate called with values 0 0 0
04-10 00:02:30.115: I/MainActivity(15795): after onclick values 5 6 8
04-10 00:02:37.550: I/MyApplication(16016): ####MyApplication on Craetet called
04-10 00:02:37.587: I/MainActivity(16016):#### MainActivity onCreate called with values 0 0 0
04-10 00:02:37.592: I/MainActivity(16016): after image selected values 0 0 0