Picking Strings from other Activitys

Asked

Viewed 102 times

4

How do I pick a String, or more, from another Activity, and then use it in another Activity, someone there can tell me?

1 answer

1


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

To add information you must use the method putExtra, that has several overloads being one of them precisely to String. When you use it you have to associate a name with 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 method getStringExtra in the Activity that has been opened and within the method onCreate.

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’re based on to get the String is not correct, or the extra does not exist, you will get null,and so you must test whether you have achieved the desired value before using it.

Documentation for the intent class, to the putExtra, and getExtra

Browser other questions tagged

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