[英]Android Intent is not passing the variable from one class to another
In Android Studio, I created a simple field called name.在 Android Studio 中,我创建了一个名为 name 的简单字段。 I want to pass this variable called name to the class called MainActivity2.我想将这个名为 name 的变量传递给名为 MainActivity2 的类。 I have declared Intents and Bundle to this.我已经为此声明了 Intents 和 Bundle。 However, the MainActivity1 class is not sending this variable to MainActivity2.但是,MainActivity1 类不会将此变量发送到 MainActivity2。 The proof of this is that the code: Toast.makeText(getApplication(), "Name:" +name, Toast.LENGTH_LONG).show();证明这一点的代码是: Toast.makeText(getApplication(), "Name:" +name, Toast.LENGTH_LONG).show();
It should show: Name: +name它应该显示:名称:+名称
The problem is that it only appears: "Name: "问题是它只出现:“姓名:”
Please, can anyone help me?拜托,有人可以帮我吗? My code is:我的代码是:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText name; Button nextPage;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.namefield);
final String name = name.getText().toString();
nextPage = findViewById(R.id.nextPage);
nextPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent senderIntent = new Intent(getApplicationContext(), MainActivity2.class);
Bundle bundle = new Bundle();
bundle.putString("name", name);
senderIntent.putExtras(bundle);
startActivity(senderIntent);
Toast.makeText(getApplication(), "Name:" +name, Toast.LENGTH_LONG).show();
}
});
}
}```
Move this line inside the setOnClickListener: final String name = name.getText().toString();
在 setOnClickListener 中移动这一行: final String name = name.getText().toString();
. .
Also If you want to check if the variable name is empty you can always use the name.isEmpty()
.此外,如果您想检查变量名称是否为空,您可以随时使用name.isEmpty()
。
Try this, in MainActivity :试试这个,在 MainActivity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.namefield);
nextPage = findViewById(R.id.nextPage);
nextPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent senderIntent = new Intent(MainActivity.this, MainActivity2.class);
String strName = name.getText().toString();
senderIntent.putExtra("NAME", strName);
startActivity(senderIntent);
}
});
}
then in MainActivity2 to get the String use this :然后在 MainActivity2 中获取字符串使用这个:
Bundle extra = getIntent().getExtras();
String newString = extra.getString("NAME");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.