nico
nico

Reputation: 1077

Android Service should hold Data for request from other Classes

I have a Service running in the Background. It fetches some strings over IP. It should truncate them and coordinate them to some variables.

So I thought:

public class Listener extends Service{
public void main(){
//fetch and preprocess data
data=fetched_string;
}

public String data=null;
public String getData(){return data;}

}

To my understanding, this should work. But how can I access this string data from another class or whats wrong with my Idea?

Or maybe there is a more elegant solution for android?

Upvotes: 2

Views: 370

Answers (2)

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

Global variable living in a singleton class is despised by architecture nazis, but really usefuill on android. It is accessible to all classes of your application, aas they run in same VM, but will not survive application restart.

To store data over restarts, there aer 3 options - shared preferences ( for small data amounts ) - sqlite , if there is a lot , data not very structured and you really need sorting / querying - serialize it to JSON with databinding solution of your choice ( shameles self advertising on: https://github.com/ko5tik/jsonserializer ) and store it in file if data is structured, and you like to have objects

Upvotes: 0

John J Smith
John J Smith

Reputation: 11921

Provided your service is running when your application is running i.e. not being called up by a BroadcastReceiver in a different process, extend the Application class, shown here and have your service set them. Then the global variable can be accessed by other classes in your application. Otherwise, have the service write them into a Sqlite database and access them from there.

Upvotes: 1

Related Questions