简体   繁体   English

如何将数据(值)从片段传递到活动

[英]How to pass data(value) from a fragment to an activity

I want to pass a specific String from a fragment to an activity to use it there.我想将一个特定的字符串从一个片段传递到一个活动以在那里使用它。 When I am using Intent and Bundle, the value is null. I have tried several methods but can't seem to make it correctly.当我使用Intent和Bundle时,这个值是null。我尝试了几种方法,但似乎无法正确设置。 Can someone help, please?有人可以帮忙吗?

In my Fragment:在我的片段中:

Intent testintent = new Intent(getActivity(), MapActivity.class);         
Bundle bundle = new Bundle();         
bundle.putString("testing", "This is a test");         
testintent.putExtras(bundle);`

And in my Activity:在我的活动中:

String message = getIntent().getStringExtra("testing");         
System.out.println("Value is : " + message);`

And this is what I am getting as a result in my console:这就是我在控制台中得到的结果:

I/System.out: Value is : null

In the Fragment:在片段中:

    val intent = Intent(this, MapsActivity::class.java)
    intent.putExtra("testing", "This is a test")
    startActivity(intent)

In the receiving Activity:在接收活动中:

    val extras = intent.extras
    if (extras != null) {
       val  receivingString = extras.getString("testing")
       System.out.println("Value is : " + receivingString)
    } else {
    
    }

Using jave:使用爪哇:

Intent intent = new Intent(getActivity(), MapActivity.class);
intent.putExtra("testing", "This is a test");
getActivity.startActivity(intent);

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

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