简体   繁体   English

Android Studio:通过另一个变量传递变量不起作用

[英]Android Studio: Passing variable through another variable doesn't work

I created a Method for my MainActivity to pass a String to my SecondActivity. 我为MainActivity创建了一个将字符串传递给SecondActivity的方法。

public void convertCurrency(View view)
{
   intent.putExtra("NO", "My String");
   startActivity(intent);
}

But in my SecondActivity in my OnCreate Method 但是在我的OnCreate方法的SecondActivity中

    Button back = (Button) findViewById(R.id.back);
    TextView t = (TextView) findViewById(R.id.first_text);

    Intent intent = new Intent(this, MainActivity.class);

    String g = intent.getStringExtra("NO");
    t.setText(g);

Nothing happens. 什么都没发生。 But Why? 但为什么?

get Your variable in this way: 以这种方式获取您的变量:

String yourVriable = getIntent().getStringExtra("NO")

don't new Your intent 不要新你的意图

Your are creating new intent. 您正在创建新的意图。

In onCreate method call 在onCreate方法中调用

String data = getIntent().getStringExtra(key);

replace Intent intent = new Intent(this, MainActivity.class); 替换Intent intent = new Intent(this, MainActivity.class); by Intent intent = getIntent(); 通过Intent intent = getIntent();

When you do intent.getStringExtra("NO"); 当你做intent.getStringExtra("NO"); your intent Object is new, so his Extra is empty. 您的意图对象是新的,因此他的附加对象为空。

You need to change the code in both the activities . 您需要在两个活动中都更改代码。 You need to create intent and put your string into it, so your code will be. 您需要创建意图并将字符串放入其中,这样您的代码就可以了。

public void convertCurrency(View view) { 
     Intent intent = new Intent(this, Main2Activity.class);
     intent.putExtra("NO","My String");                  
     startActivity(intent);
 }

Note that in the intent constructor the first argument is the current activity and the second argument will be the activity that you are starting.So in the second activity you need to recieve the string. 请注意,在Intent构造函数中,第一个参数是当前活动,第二个参数将是您正在启动的活动,因此在第二个活动中,您需要接收字符串。 Code for that will be, 的代码将是,

Button back = (Button) findViewById(R.id.back); 
TextView t = (TextView) findViewById(R.id.first_text); 
String g = getIntent().getStringExtra("NO")
t.setText(g);

I resolve the problem myself. 我自己解决问题。 There occurs an error if you have two Intent objects with the same name even if they are within separate methods. 如果您有两个具有相同名称的Intent对象,即使它们在单独的方法中,也会发生错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM