pass data between activities with intent

2020-06-28 16:21发布

My case is a little bit of special so I will explain here. I have 2 activities, first with 2 edits and 1 button and second with just a button. When pressing the button in activity 1 the program sends with intent the informations from text edits to activity 2 and displays it on activity 2. On activity 2 the button is only to get back to activity 1 and i call it like this

    Button next = (Button) findViewById(R.id.button2);

    Intent myIntent = getIntent();
    String nume = myIntent.getStringExtra("nume");
    String prenume = myIntent.getStringExtra("prenume");
    next.setText(nume + " " + prenume);

    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        }

    });

The first time i enter infos in edits they are displayed ok in activity 2, but after I come back to activity 1 and enter new values on edits on the activity 2 are displayed the values entered first time.

So the problem seems to be that the edits passed by intent wont be updated each time I press the button 1 to pass to Activity 2 starting with the second atempt.

2条回答
家丑人穷心不美
2楼-- · 2020-06-28 16:57

Navigate from First to Second:

Button next = (Button) findViewById(R.id.button2);
next.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Intent intent = new Intent(getApplicationContext(),Second.class);
        intent.putExtra("Tag", "Value");
        startActivity(intent);
        finish();
    }

});

Second to First:

 Button previous= (Button) findViewById(R.id.button);
 previous.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Intent intent = new Intent(getApplicationContext(),First.class);
        startActivity(intent);
    }

});

Second Activity on Create:

Intent i = getIntent();
String val = i.getStringExtra("Tag");
查看更多
孤傲高冷的网名
3楼-- · 2020-06-28 17:01

It seems like using an extras Bundle will be a better idea. you Implement it like this;

activity 1

 Intent pass = new Intent(ACTION_NAME);
 Bundle extras = new Bundle();
 extras.putString("nume", NUME_VAL);
 extras.putString("prenume", PRENUME_VAL);
 pass.putExtras(extras);
 startActivity(pass);

activity 2

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Bundle data = getIntent().getExtras();
     String nume = data.getStringExtra("nume");
     String prenume = data.getStringExtra("prenume");
}
查看更多
登录 后发表回答