Android : How to save data (Intent's Data)

2019-08-14 14:59发布

问题:

There is an example code that passed data by using Intent below the three Activity codes.

Activity A

public class A extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_A);
}

public void onButton1Clicked(View v) {
    Intent intent = new Intent(getApplicationContext(), B.class);
    startActivity(intent);
}

Activity B

public class B extends AppCompatActivity {

TextView tv;
ImageButton ib;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_B);

    tv = (TextView) findViewById(R.id.textView);
    ib = (ImageButton) findViewById(R.id.imageButton);
    ib.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(B.this, C.class);
            startActivityForResult(intent, 2);
        }
    });

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 2) {
        if (data != null) {
            String message = data.getStringExtra("DATA");
            tv.setText(message);
        }
    }
}

public void onButton2Clicked(View v) {
    Intent intent = new Intent(getApplicationContext(), C.class);
    startActivity(intent);
}

Activity C

public class C extends AppCompatActivity {

EditText et;
Button btn;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_C);

    et = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String data = et.getText().toString();
            Intent intent = new Intent();
            intent.putExtra("DATA", data);
            setResult(2, intent);
            finish();
        }
    });
}

The order of activity is A - B - C.

In A, there is a Button that can move to B, and in B there are a Button(can move to C) and TextView. In C, a Button(can move to B again) and EditText.

For example, Using 'startActivityForResult' I have output as TextView(B) that received a text which was input by EditText in C. But after moving B into A(Back), an insertion of TextView gets disappeared when entering to B again. In addition, even if entering into C, there is no insertion of EditText, too.

I would really need and know 'Save code' into variable by inputting as EditText when pressing a button in C.

In this case, HOW can I add ‘Code’ the remain the insertion value either the insertion value remains by quitting the application or moves to Activity that received DATA like A?

Thanks for your cooperation and concern.

回答1:

To maintain the state of your activity, you have to override onSaveInstanceState method. Store the value of your TextViews and EditText in this method. For example, let's talk about Activity B. In activity B you would do something like this:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    String text = tv.getText().toString();
    savedInstanceState.putString("mytext", text);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Then in your onCreate do this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
   // Set Content View and initialize the views
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        String mytext = savedInstanceState.getString("mytext");
        tv.setText(mytext);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

You can read more about Recreating an Activity.



回答2:

You can store intent's data using following way.. Your example seems confusing on how you passing the data and you have two methods in ActivityB handing the Intent. (onButtonClicked and StartActivityForResult())

Here's simple example

Define unique string to save your Intent's data in - ActivityA

public final static String EXTRA_MESSAGE ="myMessage";

below method will open the ShowMessage Activity showing the message you type in EditText view.

 public void sendMessage(){
 Intent intent = new Intent(this, ShowMessage.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

Here's how you can retrieve that data in ShowMessage activity. -ActivityB.

Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
 //EXTRA_MESSAGE is a unique string that holds the message typed in TextView
  TextView receiveMessage = findViewById(R.id.sentMessage);
  receiveMessage.setText(message); //would set the message typed in ActivityA

Now when you get back and if you still want your EditText to have the previous string entered, you can do as the answer given by Eric B.

//Saving the value
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    String myMessage = editText.getText().toString();
    outState.putString("myMessage", myMessage);

}

in onCreate(), you can retrieve as follows

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

   if (savedInstanceState != null){

        String myMessage = savedInstanceState.getString("myMessage","");
        editText.setText(myMessage);
    }

Also one thing recommended is resultCode == RESULT_OK for validation of intent.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == 2 && resultCode == RESULT_OK) {
    if (data != null) {
        String message = data.getStringExtra("DATA");
        tv.setText(message);
    }
}