In Android: How to get variables / data from one screen to another?

In android: I'm trying to take data from one action / screen to another.

Let's say I add two numbers. I am composing my first screen (xml) with 2 kinds of EditText, two shortcuts and an OK button. Now I want to add the numbers that I entered into the EditText views. Let's say I enter 2 and 2 (2 + 2 = 4).

Now, when I click the “OK” button, I want a new screen / activity to appear, and just show me the answer (4). Am I using global vars for this? Any help would be appreciated.

+4
source share
4 answers

First activity

Intent myIntent = new Intent(); myIntent.putExtra("key", "value"); startActivity(myIntent); 

New activity

 Intent myIntent = getIntent(); // this is just for example purpose myIntent.getExtra("key"); 

Browse the various types you can use on the Android Dev site

Note. If you are looking for a way to share object / data around the world, you can extend the Application class. Check How to declare global variables in Android? (answer by Soonil)

+23
source

I believe that you are launching the "next screen" with Intent (this is how it should be done).

In Intent you can pass extras (putExtra) and in onCreate in the “next step” you can getIntent().getXExtra() (replace X with the field type)

+4
source

Take a look at some examples of examples (from common tasks and how to make them in Android):

basically, you use myIntent.putExtra (...) to send data (maybe String, Int, Boolean, etc.) to the other side (another action) ...

then the result will be passed back to the calling ActivityActivityResult () method:

 protected void onActivityResult(int requestCode, int resultCode, Intent data){ // See which child activity is calling us back. switch (resultCode) { case CHOOSE_FIGHTER: // This is the standard resultCode that is sent back if the // activity crashed or didn't doesn't supply an explicit result. if (resultCode == RESULT_CANCELED){ myMessageboxFunction("Fight cancelled"); } else { myFightFunction(data); } default: break; } 

N.

+2
source

Sample from my project. We must use the bundle to get data.

Use the code to / from the first action, specifying the data. You can set all data types, including arrays.

 Intent i = new Intent(this, LanguageSetting.class); i.putExtra("From", 1); startActivity(i); 

To retrieve the data, write the code below in the new / second step.

 Intent myIntent = getIntent(); Bundle b = myIntent.getExtras(); intCameFrom = b.getInt("From"); 
0
source

Source: https://habr.com/ru/post/1302585/


All Articles