我想設計一個Android應用程序,在那個應用程序中,我已經將數據從First Activity發送到第二個Activity。在第二個活動,我使用這個代碼如何通過使用onSaveInstanceState()和onRestoreInstanceState()方法在EditText上保存所需的數據
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
保存在應用程序移動到橫向到縱向模式,但在我的應用程序,即使我使用這兩個數據,但該數據不被保存。在旋轉時,數據正在被EditText
視圖中的應用程序破壞。
請檢查下面的代碼,給我在哪裏做的錯誤保存數據
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText name,age;
TextView text_name,text_age;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText) findViewById(R.id.name);
age=(EditText) findViewById(R.id.age);
text_name=(TextView) findViewById(R.id.name_edit);
text_age=(TextView) findViewById(R.id.name_age);
btn=(Button) findViewById(R.id.click);
//Button Click to send data to another activity
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle bundle=new Bundle();
String user_name=name.getText().toString();
String user_age=age.getText().toString();
bundle.putString("UName",user_name);
bundle.putString("UAge",user_age);
Intent intent=new Intent(MainActivity.this,SecondClass.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
SecondClass.java
的建議public class SecondClass extends Activity {
EditText name,age;
TextView text_name,text_age;
String namer,ager;
private String savedName,savedAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity_layout);
name=(EditText) findViewById(R.id.name);
age=(EditText) findViewById(R.id.age);
text_name=(TextView) findViewById(R.id.name_edit);
text_age=(TextView) findViewById(R.id.name_age);
if (savedInstanceState!=null)
{
savedInstanceState.get(savedName);
name.setText(savedName);
savedInstanceState.get(savedAge);
age.setText(savedAge);
}
if (savedInstanceState==null)
{
Intent i=getIntent();
Bundle bundle=i.getExtras();
namer=bundle.getString("UName");
name.setText(namer);
ager=bundle.getString("UAge");
age.setText(ager);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(savedName,namer);
outState.putString(savedAge,ager);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState!=null)
{
savedInstanceState.get(savedName);
name.setText(savedName);
savedInstanceState.get(savedAge);
age.setText(savedAge);
}
if (savedInstanceState==null)
{
Intent i=getIntent();
Bundle bundle=i.getExtras();
namer=bundle.getString("UName");
name.setText(namer);
ager=bundle.getString("UAge");
age.setText(ager);
}
}
}
嘗試移動'super.onSaveInstanceState(outState);'這個語句後'outState.putString(savedAge,幾歲);' –