How to pass variables from a new intent back to th

2019-09-12 20:54发布

问题:

I know my title may be a little convoluted but I am really quite confused and couldn't think of a better title.

My problem: I have a main class that creates a new intent. This new intent is basically just a popup with an EditText in it and one button.

My main class creates the intent as so:

Intent i = new Intent("com.stevedub.GS.INPUTMPG");
startActivity(i);

What I want to do is somehow get the data that the user inputs into the EditText in the new Intent and use that integer in my main class to do calculations. I just have no idea how to accomplish this.

This is the code I have for my second class that is used for the new Intent.

public class InputMPG extends Activity {

EditText mpg;
Button b;
String ans;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.inputmpg);

    mpg = (EditText) findViewById(R.id.MPGinput);
}

Now the new activity is just the barebones of a class because I don't know if I should be initializing the button and the EditText in that class or no. Anyone pointing me in the right direction would be greatly appreciated.

Thanks in advance.

回答1:

What you will need to do is a combination of things.

First, start the activity using:

Intent intent = new Intent("com.stevedub.GS.INPUTMPG");
startActivityForResult(intent, RETURN_CODE);

Then in your InputMPG class, set the Return value with the following:

Intent returnIntent = new Intent();
returnIntent.putExtra("result", editText.getText());
setResult(RESULT_OK, returnIntent);

Finally to receive the data in your original Activity use the onActivityResult method:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RETURN_CODE && resultCode == RESULT_OK) {
        //get value from intent
    } 
}


回答2:

Try to use startActivityForResult()