2

I am trying to pass a String from my MainActivity to a non-activity class (A Notification Service) So that I can customise the notification message. I have tried using Intent however it won't work because it is a non-activity based class. What is the best why to do this?

I am currently trying to use a global variable but its not working.

MainActivity.java

private String var;
private String a = "Pumpkin";

public String getVar(){
    return var;
}
public void setVar(String a){
    var = a;
}

NotificationService.java

  MainActivity b = ((MainActivity)getApplicationContext());
  String var = b.getVar();

This crashes the app when even I call the variable var in NotificationService.java

Whereslee
  • 123
  • 10

4 Answers4

3

1.You can try by making static variable, and call with Class refenrence in any where.

 public static  String a = "Pumpkin";//Declare in MainActivity
 Use it: String var = MainActivity.a;

2. Pass in Intent as extras and then get extras in where intent recived.

  startActivity(new Intent(MainActivity.this, PropertyListviewActivity.class).putExtra("Key", "Value"));

Recive :

 if (intent != null)
        if (intent.getExtras() != null)
            if (intent.getExtras().getString("Key") != null) {
                String recivedString= intent.getExtras().getString("Key");

3.Keep in Shared Preferences and retrive where ever you want(not good practise).

4.If Not an Android Component class try pass in Contractor.

Guruprasad
  • 931
  • 11
  • 16
  • 1
    I would strongly suggest using the second option. The first and the third are both essentially global variables and they make the application much harder to maintain. The Intent's extras are the closest thing to a method parameter. You don't need all those null checks if you're sure that you're passing the parameter. – DariusL Jul 26 '15 at 06:53
1

Try an event bus Green Robot or Otto Event Bus both are excellent options.

Niraj Adhikari
  • 1,678
  • 2
  • 14
  • 28
0

You are trying to cast app Context to Activity. It crashes, cause app context is not an activity. You should use handleIntent or binder in your service to transport data. http://developer.android.com/guide/components/bound-services.html#Basics

Semyon Tikhonenko
  • 3,872
  • 6
  • 36
  • 61
-1

you can do this task by saving data to application level variable or save it in sharedpreference.

To save data in application level make a static variable like

public static DatatypeYouDesire(String/int) cachedData;

now when you want to store data jst initialize this varaible with the data you want to store like

YourApplictionClass.cachedData = "your data to be stored";

similarly you can use this data by accesing YourApplicationClass.cacheData

Ram Mandal
  • 1,899
  • 1
  • 20
  • 35