Pass data from one Activity to another without starting it?

1

I'm creating an Android App, I need to pass data of type String from the first activity (when started), to a third activity. But without starting it. In case I take the user ID on the first screen and use it to register the message, implementing it in the database.

Code:

//recebo assim do banco através do php
//Primeira Tela
String[] dados = result.split(",");
Intent abreHome = new Intent(MainActivity.this, HomeActivity.class);
abreHome.putExtra("id_user", dados[1]);

//Segunda Tela
//Recebo as Informações e repasso para a terceira
Intent abrePost = new Intent(HomeActivity.this, PostActivity.class);
String id_user = getIntent().getExtras().getString("id_user");
startActivity(abrePost);
String txt = "";
txt = id_user.toString();
Bundle bundle = new Bundle();
bundle.putString("txt", txt);
abrePost.putExtras(bundle);
startActivity(abrePost);

//Terceira Tela
//Onde recebo o ID
//Porém quando eu executo, pela primeira vez a mensagem é salva, a segunda diz //que parou a Activity, e retorna para a segunda Activity.
//A primeira mensagem é salva, a segunda não, a terceira sim, a quarta não.
//E assim susessivamente
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String txt = bundle.getString("txt");
id_user = getIntent().getExtras().getString("txt");
    
asked by anonymous 09.09.2016 / 02:39

2 answers

2

You are starting the same activity more than once, one without the information you want to pass on and the other with this information:

//Segunda Tela
//Recebo as Informações e repasso para a terceira
Intent abrePost = new Intent(HomeActivity.this, PostActivity.class);
String id_user = getIntent().getExtras().getString("id_user");
startActivity(abrePost); //Inicia sem mensagem
String txt = "";
txt = id_user.toString();
Bundle bundle = new Bundle();
bundle.putString("txt", txt);
abrePost.putExtras(bundle);
startActivity(abrePost); //Inicia com mensagem

To correct, it is only necessary to start the activity when it has the information that will be passed on. It would look like this:

//Segunda Tela
//Recebo as Informações e repasso para a terceira
Intent abrePost = new Intent(HomeActivity.this, PostActivity.class);
String id_user = getIntent().getExtras().getString("id_user");
String txt = "";
txt = id_user.toString();
Bundle bundle = new Bundle();
bundle.putString("txt", txt);
abrePost.putExtras(bundle);
startActivity(abrePost);

NOTE: Remember to control the activity completion initialization because the approach used by you in this code snippet will generate memory leak.

    
09.09.2016 / 02:49
0

You inadvertently called startActivity(abrePost);

    
09.09.2016 / 15:05