How to use getIntent() in a class that does not ex

2019-07-06 09:02发布

I am trying to pass a String from a class "Play" which extends Activity by using:

Bundle data = new Bundle();
Intent i = new Intent(Play.this, Receive.class);
String category;

data.putString("key", category);
i.putExtras(data);

Then, the "Receive" class which is a non Activity class and does not extend Activity will receive the String from "Play".

But when I try to receive the data using this code:

Bundle receive = new Bundle();
String passed;

receive = getIntent().getExtras();
passed = receive.getString("key");

I get an error on the word "getIntent()" and suggests me to create a method getIntent().

What is the possible solution to this problem? THANKS!

3条回答
女痞
2楼-- · 2019-07-06 09:14

You cannot getIntent(); from within a class that does not extend Activity. As Sprigg mentioned you would have to use other means of communication between the classes.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-06 09:29

You should use a public static variable and use it to store data and fetch data from other class.

As intents don't work without extending Activity class in Android.

In your case , it would be like.

public static category="some category";

To access in another class ,

String dataFromActivity=NameOFClassWhereCategoryIsDefined.category;

查看更多
戒情不戒烟
4楼-- · 2019-07-06 09:34

Intent is not nessesary here. You can just do something like this:

Play.class :

public String getCategory() {
    return category;
}

and in Receiver.class :

Play playObject = new Play();
passed = playObject.getCategory();

Or you can use static field as pKs mentioned but it's not always a good pattern.

查看更多
登录 后发表回答