如何对字符串数据使用 putExtra() 和 getExtra() [英] How to use putExtra() and getExtra() for string data
问题描述
谁能告诉我如何使用 getExtra()
和 putExtra()
来实现意图?实际上我有一个字符串变量,比如str,它存储一些字符串数据.现在,我想将此数据从一个活动发送到另一个活动.
Can someone please tell me how exactly to use getExtra()
and putExtra()
for intents? Actually I have a string variable, say str, which stores some string data. Now, I want to send this data from one activity to another activity.
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer = null;
i.putExtra(strName, keyIdentifer );
然后在 SecondScreen.java
and then in the SecondScreen.java
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
TextView userName = (TextView)findViewById(R.id.userName);
Bundle bundle = getIntent().getExtras();
if(bundle.getString("strName")!= null)
{
//TODO here get the string stored in the string variable and do
// setText() on userName
}
}
我知道这是一个非常基本的问题,但不幸的是我被困在这里.请帮忙.
I know it is very basic question but unfortunately I am stuck here. Please help.
谢谢,
这里我试图从一个屏幕传递到另一个屏幕的字符串是动态的.那就是我有一个 editText,无论用户键入什么,我都可以在其中获取字符串.然后在 myEditText.getText().toString()
的帮助下.我将输入的值作为字符串获取,然后我必须传递这些数据.
Here the string which I am trying to pass from one screen to the other is dynamic.
That is I have an editText where I am getting string whatever user types. Then with the help of myEditText.getText().toString()
. I am getting the entered value as a string then I have to pass this data.
推荐答案
用这个来放置"文件...
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = null;
i.putExtra("STRING_I_NEED", strName);
然后,要检索该值,请尝试以下操作:
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
这篇关于如何对字符串数据使用 putExtra() 和 getExtra()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!