Pick up Strings from other Activitys [closed]

4

How do I get a String, or more, from another Activity, and then use it in another Activity, does anyone there know how to tell me?

    
asked by anonymous 24.10.2017 / 05:40

1 answer

1

To transfer information between activities, you must use Intent itself, which has several methods to add and obtain information.

To add information you must use the putExtra method, which has several overloads , one of them precisely for String . When you use it, you must associate a name with the String you are sending:

Activity1.java :

String minhaString = "algum texto nesta String";

Intent i = new Intent(Activity1.this, Activity2.class); //Activity1 abre a Activity2
i.putExtra("nomeAssociado", minhaString); //colocar a String na informação a enviar
startActivity(i); //abrir a Activity2

To get the saved information use the getStringExtra method in the Activity that was opened and within the onCreate method.

Activity2.java :

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

    Intent intent = getIntent(); //obter o Intent enviado

    //apanhar a String enviada da Activity1 com base no nome associado
    String stringDaActivity1 = intent.getStringExtra("nomeAssociado");

If the name you are using to fetch String is not correct, or the extra name does not exist, you will get null , so you should test if you were able to get the desired value before using it.

Documentation for the Intent class , for putExtra , and getExtra

    
24.10.2017 / 11:44