Pass data from one Activity to another without starting it?

Asked

Viewed 899 times

1

I’m creating an App for Android, I need to pass String type data from the first Activity(when started), to a third Activity. But without starting it. In case I get the user ID on the first screen and use 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");

2 answers

2


You are starting the same Activity more than once, one without the information you wish to pass on and the other with that 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 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 initialization of activities because the approach used by you in this code snippet will generate memory Leak.

0

You accidentally called twice the startActivity(abrePost);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.