从另一个活动中获取数据

Tay*_*eer 7 android android-intent

还在研究我的android技能.

我的问题是我的数据库中有一个标签,其中包含一个旋转器中的名称,当我点击标签时,会出现一个对话框并给出三个选择:1.更新.2.删除.3.取消 我完成了第二个和第三个选择,但是在更新中遇到了这个问题; 我转到另一个具有editText和2个按钮,保存和取消的活动,我希望保存按钮从putExtra中的editText获取数据并将其发送回相同的先前活动并使用来自editText.

我感谢任何帮助.提前致谢.

fla*_*yte 12

在您的第二个活动中,您可以使用该方法从第一个活动中获取数据getIntent(),然后getStringExtra(),getIntExtra()...

然后,要返回到第一个活动,您必须使用setResult()带有intent数据的方法作为参数返回.

要在第一个活动中获取第二个活动的返回数据,只需覆盖该onActivityResult()方法并使用意图获取数据.

第一项活动:

//In the method that is called when click on "update"
Intent intent = ... //Create the intent to go in the second activity
intent.putExtra("oldValue", "valueYouWantToChange");
startActivityForResult(intent, someIntValue); //I always put 0 for someIntValue

//In your class
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //Retrieve data in the intent
    String editTextValue = intent.getStringExtra("valueId");
}
Run Code Online (Sandbox Code Playgroud)

第二项活动:

//When activity is created
String value = intent.getStringExtra("oldValue");
//Then change the editText value

//After clicking on "save"
Intent intent = new Intent();
intent.putExtra("valueId", value); //value should be your string from the edittext
setResult(somePositiveInt, intent); //The data you want to send back
finish(); //That's when you onActivityResult() in the first activity will be called
Run Code Online (Sandbox Code Playgroud)

不要忘记使用该startActivityForResult()方法开始第二个活动.


Ael*_*exe 5

您必须将这些信息作为附加信息传递。

传递信息

Intent i = new Intent();
i.setClassName("com.example", "com.example.activity");
i.putExtra("identifier", VALUE);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

获取信息

Bundle extras = getIntent().getExtras();
String exampleString = extras.getString("identifier");
Run Code Online (Sandbox Code Playgroud)