java - GetExtra Android 不起作用

标签 java android android-activity get

我是 android 世界的新手,所以我开始通过创建一个“Keep”应用程序来练习。因此,正如您想象的那样,我可以添加注释。问题就在这里,我的主要 Activity 在这里:

@Override
protected void onResume() {
    super.onResume();
    if (newNote) {
        newNote = false;
      findViewById(R.id.note)).setText(intentNewNote.getStringExtra("toto"));
    }
}

public void addNotes(View view) {
    newNote = true;
    intentNewNote = new Intent(this, newNote.class);
    startActivity(intentNewNote);
}

所以我有一个调用 onClick addNotes 的按钮,这里是 newNote 类 -
 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.new_note);
    intent = this.getIntent();
}

 @Override
protected void onDestroy() {
    intent.putExtra("toto", "tototookiklojlojlllllllllllllllllllllllllllllto");
    super.onDestroy();
}

toto Extra是一个测试,但它不能打印,这样就可以了
 @Override
protected void onResume() {
    super.onResume();
    if (newNote) {
        newNote = false;
        intentNewNote.putExtra("toto", "dzazda");
        ((TextView) findViewById(R.id.note)).setText(intentNewNote.getStringExtra("toto"));
    }
}

因此,当我将额外内容放在另一个 Activity 中时,它不起作用唯一的解释是我对 addNotes 类的 Intent 不一样。
有人有想法吗?

谢谢你。

最佳答案

我试图了解您在做什么,并且我相信您正试图从您的第二个 Activity 中返回一些信息,但您使用的 Intent 与您收到的相同。它在android上的工作方式是这样的:

从您的 FirstActivity 调用 SecondActivity 使用 startActivityForResult() 方法

例如:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
在您的 SecondActivity 中设置您想要返回给 FirstActivity 的数据。如果您不想返回,请不要设置任何内容。

例如:在 secondActivity 如果你想发回数据:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

如果您不想返回数据:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

已编辑

现在在您的 FirstActivity 类中为 onActivityResult() 方法编写以下代码。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {
    if(resultCode == Activity.RESULT_OK){
        String result=data.getStringExtra("result");
    }
    if (resultCode == Activity.RESULT_CANCELED) {
        //Write your code if there's no result
    }
}
}//onActivityResult

关于java - GetExtra Android 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45089450/

相关文章:

java - Eclipse控制台错误链接将我发送到错误的项目

android - Google Play Billing 测试卡在制作后仍会显示

安卓错误 "unable to find explicit activity class"

Android 将任务置于最前面

java - 空闲 AWS 实例上的 Web 服务中出现 CommunicationsException

java - 我什么时候应该使用 Double.longBitsToDouble(...) 而不是简单地将 long 转换为 double ?

java UnsatisfiedLinkError awt.image

java - 将 JSONObject 解析为自定义类

android - 您真的需要检查 Google Play 服务才能使用 AdMob 吗?

android - 将 GoogleApiClient 对象从一个 Activity 传递到另一个 Activity