How to pass variables from a new intent back to the class that created it in android

亡梦爱人 提交于 2019-12-13 05:41:00

问题


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()



来源:https://stackoverflow.com/questions/12468610/how-to-pass-variables-from-a-new-intent-back-to-the-class-that-created-it-in-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!