How do I use getIntent () on a class that doesn't extend Activity?

I am trying to pass a String from a "Play" class that extends an Activity using:

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

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

      

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

But when I try to get data with this code:

Bundle receive = new Bundle();
String passed;

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

      

I get the error "getIntent ()" and asks me to create a getIntent () method.

What is the possible solution to this problem? THANK!

+3


source to share


3 answers


Intention is not required here. You can simply 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 a static field as pKs, but that's not always a good pattern.

+5


source


You have to use public static variable

and use it to store data and retrieve data from another class.

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

In your case it will be similar.



public static category="some category";

To access in another class,

String dataFromActivity=NameOFClassWhereCategoryIsDefined.category;

+1


source


You cannot getIntent (); from a class that does not extend Activity. As Sprigg said, you will have to use other ways to communicate between classes.

0


source







All Articles