1

Currently I have an app which has code in its main activity that reads data from an xbee. My problem is that I want to relay this data to 4 different threads in 4 different classes throughout my project. I looked into bundling it, but that seems like a one time data transfer, not a stream of it.

One idea I had was to write the data to a string called messages and then have a getMessages() function, but I ran into a problem calling a static method from a non-static class or vise versa.

JohnF
  • 23
  • 8

4 Answers4

0

Have you considered using SharedPreferences or extending Application? SharedPreferences will let you store basic types (String, int, boolean, etc) in persistent storage. Application can be extending to store variables / methods that can be accessed anywhere in your program. For example, MyApplication app = (MyApplication)getApplicationContext();

Are you looking to modify this stream of data in each of your threads, or simply read a value and modify data separately? You may want to setup some boolean flags to ensure you aren't accessing / modifying data that isn't safe to perform those operations on. Hope that helps! Let me know if I can provide a code example for clarity.

Zack Matthews
  • 409
  • 2
  • 11
  • In that case, either `SharedPreferences` or extending `Application` will work perfectly. Which one is up to you, but if you wanted my advice I would say you probably want to use `SharedPreferences` if your data types are simple or Application if you're dealing with more complicated objects. You can view the [SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html) and the [Application](http://developer.android.com/reference/android/app/Application.html) documentation if you'd like to learn more. – Zack Matthews Jul 15 '15 at 15:44
0

one way of doing it to simply make your main activity write into android.database.sqlite and others will simply read from it

since not sure how your code layout is I just refer you the documetation page :

http://developer.android.com/reference/android/database/sqlite/package-summary.html

nafas
  • 5,283
  • 3
  • 29
  • 57
0

You can create one handler for each of your threads and then post messages on all the handlers. Below is the link which creates an Handler and post messages from the handler reference:-

using a Looper in a Service is the same as using a separate thread?

Community
  • 1
  • 1
Ankit
  • 229
  • 1
  • 6
0

You can implement observer pattern to solve this.Make the four classes as observers and the activity as subject.

Expose a api like onDataChanged(byte[] data) which will be called whenever your activity has some new data.

To learn more about observe pattern refer-https://en.wikipedia.org/wiki/Observer_pattern

You can also have a look at classic producer consumer problem if you want synchronization https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

rupesh jain
  • 3,410
  • 1
  • 14
  • 22