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!
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.
You should use a
public static variable
and use it to store data and fetch data from other class.In your case , it would be like.
public static category="some category";
To access in another class ,
String dataFromActivity=NameOFClassWhereCategoryIsDefined.category;
Intent is not nessesary here. You can just do something like this:
Play.class :
and in Receiver.class :
Or you can use static field as pKs mentioned but it's not always a good pattern.