简体   繁体   中英

whats wrong with this code? it always returns savedInstanceState as null

This code always returns savedInstanceState as null

public class DemoidActivity extends Activity implements OnClickListener, android.view.View.OnClickListener  {

EditText t1=null;
EditText t2=null;
EditText t3=null;
EditText t4=null;
String data1 = null,data2=null,data3=null;
/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t1=(EditText)findViewById(R.id.editText1);
    t2=(EditText)findViewById(R.id.editText2);
    t3=(EditText)findViewById(R.id.editText3);
    t4=(EditText)findViewById(R.id.editText4);
    Button b1=(Button)findViewById(R.id.button1);
    Button b2=(Button)findViewById(R.id.button2);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);



}

Their is nothing wrong with the code as such. The reason why you are getting the savedInstanceState as null in your onCreate() method is because your activity is created for the first time and so there won't be any saved state as such.

It will only be set if you implement the method onSaveInstanceState(). http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle )

It means that your activity's state is never saved.
Try to override the onSaveInstanceState() method:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //Put your stuff in the bundle
}

Then use it to retrieve data/activity sate whether in the onCreate() method or in the onRestoreInstanceState() one:

if (savedInstanceState != null) {
    //Retrieve data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM