I am trying to add an observer in my activity but it never seems to get triggered.
I have a button on my app which makes a sensor connected to my phone start measuring data when the sensors are measuring it hits a callback in my XsDevice() class.
Here is the code in my XsDevice() class
private MutableLiveData<ArrayList<Float>> accelerationData = new MutableLiveData<>();
public LiveData<ArrayList<Float>> freeAccDataLiveData = accelerationData;
#Override
public void onXsensDotDataChanged(String s, XsensDotData xsensDotData) {
ArrayList<Float> result = new ArrayList();
for (Float freeAcc: xsensDotData.getFreeAcc()) {
result.add(freeAcc);
}
accelerationData.postValue(result);
}
When the callback function is hit I am using postValue(result) to update the accelerationData variable, this is where me being a new to android development comes in.
I am presuming after I post the value the freeAccDataLiveData variable is updated and this is what I am observing.
Here is my observer code in my activity
private XsDevice xsDeviceClass = new XsDevice();
protected void onCreate(Bundle savedInstanceState) {
...
xsDeviceClass.freeAccDataLiveData.observe(this, new Observer<ArrayList<Float>>() {
#Override
public void onChanged(ArrayList<Float> freeAccData) {
for(int i = 0; i < freeAccData.size(); i++){
Log.d("Free Acceleration Data", String.valueOf(freeAccData.get(i)));
}
}
});
}
The ... is just a placeholder for the standard onCreate code I haven't included.
The issue I am having is Log.d("Free Acceleration Data", String.valueOf(freeAccData.get(i))); is never logged which must mean the observer isn't working. If I added this log directly to the callback function it works fine but I need to get the data in my MainActivity
Is there something simple I might have missed?
The observer of livedata will be called only when data is changed by set or post. Thus, if you did not initialize the value in the XsDevice class, it won't be called until data is assigned.
If you want to get callback in OnCreate method by default, need to set the default value of accelerationData like this. Then, you can get callback right after you register an observer.
class XsDevice {
private MutableLiveData<ArrayList<Float>> accelerationData = new MutableLiveData<>();
public LiveData<ArrayList<Float>> freeAccDataLiveData = accelerationData;
public XsDevice() {
accelerationData.postValue(new ArrayList<>());
}
...
}
Also, please make sure onXsensDotDataChanged is called as you expected and freeAccData is not empty. Otherwise, you cannot see the log even though it is called.
Related
Would like to have your help on my weird problem that currently I am facing. I tried for couple of days but no luck and finally decided to post here to take help.
I created a Snapshot Listener attached to a Collection in Firebase defined as follows :-
public class FirebaseTypingStatusLiveData extends LiveData<List<documentSnapshot>> {
// Logging constant
private static final String TAG = "FirebaseQueryLiveData";
// Document Reference
private final DocumentReference documentReference;
// Listener
private final MyDocumentListener listener = new MyDocumentListener();
// Handler
private final Handler handler = new Handler();
private ListenerRegistration listenerRegistration;
// Flag to remove listener
private boolean listenerRemovePending = false;
private MutableLiveData <List<documentSnapshot> mutableLiveData = new MutableLiveData<>();
// Constructor
public FirebaseTypingStatusLiveData(DocumentReference documentReference) {
this.documentReference = documentReference;
}
public LiveData<List<documentSnapshot>> checknow(){
// Add listener
if (!Listeners.LIVESAMPLE.containsKey(documentReference)) {
listenerRegistration = documentReference.addSnapshotListener(listener);
Listeners.LIVESAMPLE.put(documentReference, listenerRegistration);
} else {
listenerRegistration = Listeners.LIVETYPINGSTATUSSAMPLE.get(documentReference);
}
return mutableLiveData;
}
// Listener definition
private class MyDocumentListener implements EventListener<DocumentSnapshot> {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable
FirebaseFirestoreException e) {
Log.d(TAG, "onEvent");
// Check for error
if (e != null) {
// Log
Log.d(TAG, "Can't listen to query snapshots: " + documentSnapshot
+ ":::" + e.getMessage());
return;
}
setValue(documentSnapshot);
mutableLiveData.setValue(documentSnapshot);
}
}
}
}
The snapshot reads the data perfectly and advised as and when data is available.
The snapshot data is getting displayed 1. in Fragment (not part of Activity that i am talking about) 2. Activity through two view models that have the same code as follows :
#NonNull
public LiveData<List<documentSnapshot>> getDataSnapshotLiveData() {
Firestore_dB db = new Firestore_dB();
DocumentReference docref = db.get_document_firestore("Sample/"+docID);
FirebaseTypingStatusLiveData firebaseTypingStatusLiveData = new
FirebaseTypingStatusLiveData(docref);
return firebaseTypingStatusLiveData.checknow();
}
The Fragment & Activity code is also same except changing owner which are as follows :-
LiveData<List<documentSnapshot>> liveData = viewmodel.getDataSnapshotLiveData();
liveData.observe(this, new Observer<List<documentSnapshot>>() {
#Override
public void onChanged(DocumentReference docreef) {
String name = docreef.get("name");
stringname.setText(name); // The text is displaying either in Fragment or in Activity but not in both.
});
My problem is i need data in both i.e. Fragment & Activity whereas I am getting data either in Fragment or in Activity depending upon the code which I commented.
Kindly advise where I am making mistake. Thanks in Advance
Honestly, I am not sure that my answer wouldn't lead you away to the false way, but you can try.
My guess is that your problem could be somehow connected with ViewModel sharing.
There is a well-known task How to share Viewmodel between fragments.
But in your case, that can't help, because you have to share ViewModel between activities (now you have two separate ViewModels and that could be problem with Firestore EventListeners).
Technically you can share ViewModel between activities (I haven't try since usually I use Single activity pattern). For that as a owner parameter in ViewModelProvider constructor you can set instance of your custom Application class (but you have implement interface ViewModelStoreOwner for it). After that both in your activity and in your fragment you can get the same ViewModel with the Application class-instance:
val sharedViewModel = ViewModelProvider(mainApplication, viewModelFactory).get(SharedViewModel::class.java)
I made LiveData static that listens to changes in source data and provide updated content were ever required in different Activity.
I am a beginner so apologies for a possible silly question.
I am trying to retrieve data from a Firebase database. This works but I cannot assign the value to a string variable for use later on.
This is the asynchronous call to the database which returns the right result. (The data its querying from is static so I don't really need an asynchronous call but as far as I am aware, I don't have another option).
public static void getAnimalDetails(String strColl, final String strQueryField, final String strQueryValue,
final MyCallBack myCallback){
mfirebaseDb.collection(strColl)
.whereEqualTo(strQueryField, strQueryValue)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String strResult = document.get("animal_class").toString();
Log.d(TAG, "SSSS:" + strResult );
myCallback.onCallback(strResult);
}
}
}
});
}
This is the callback function passed to the method above.
public interface MyCallBack {
void onCallback(String strValFromAsyncTask);
}
Then this is where I call the asynch task and try and access the data from the callback.
This method fires on a button click
I can see via the log that the right value is populated in strAnimalClass (which is a global variable)
But when I try to use strAnimalClass outside of the call back it is null.
getAnimalDetails("animals", "animal_common_name", animal, new MyCallBack() {
#Override
public void onCallback(String strValFromAsyncTask) {
strAnimalClass = strValFromAsyncTask;
Log.d(TAG, "mmmmm:" + strAnimalClass );
}
});
Can anyone help with how to get a value like this out of the async / callback environment for use later on?
Thank you
You can't use the value outside of the callback. Or more specifically, you can use the value outside of the callback, but not before the callback has been called. This same rule applies to Firebase's onComplete and to your custom onCallback method.
You can verify that with a few log lines:
Log.d(TAG, "Before calling getAnimalDetails")
getAnimalDetails("animals", "animal_common_name", animal, new MyCallBack() {
#Override
public void onCallback(String strValFromAsyncTask) {
Log.d(TAG, "Inside onCallback");
}
});
Log.d(TAG, "After calling getAnimalDetails")
When you run this code, it logs:
Before calling getAnimalDetails
After calling getAnimalDetails
Inside getAnimalDetails
So while you can access strAnimalClass after the code that calls getAnimalDetails, it won't have the expected value yet, because onCallback wasn't called yet.
For this reason any code that needs the value(s) from the database will need to be inside onComplete or inside onCallback, or be called from within there.
Also see:
How to check a certain data already exists in firestore or not
getContactsFromFirebase() method return an empty list
Setting Singleton property value in Firebase Listener
I am calling methods in viewModel to set data on my mutable live data like below and they are being called one after the other exactly like below:
viewModel.onCountrySelected(country);
viewModel.onLanguageSelected(language);
Then in the view model I set the data on the mutable live data is I am observing in my fragment. The methods in my view model are below:
public void onLanguageSelected(int type) {
clickType.setValue(type);
}
public void onCountrySelected(int type) {
clickType.setValue(type);
}
clickType is my Mutable Live data. Now the problem is that my onChanged is only called once and that too only for the last value that I set on clickType.
If I am not wrong I onChanged should be triggered twice since I am setting the value on the clickType twice.
private void initLiveData()
{
clickType = new MutableLiveData<>();
clickType.setValue(0);
}
initLiveData is where I am initialising the MutableLiveData. Also I am calling the initLiveData after setting the veiwModel variable to the layout.
In the fragment:
binding.setViewModel(viewModel);
viewModel.initLiveData()
viewModel.getClickType().observe(this, new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer type) {
handleClicks(type);
}
});
I'm just getting into Android Development using Xamarin with Visual Studio 2015 Update 3. I'm trying to create a simple spinner, but something is going very, very wrong with the order of execution in the debugger.
In shared code, I have an options class that contains common values for dropdowns, etc.
public interface IOptionsCache : INotifyPropertyChanged
{
// is not observable collection on purpose, the entire list is replaced
// when data is fetched from the server
IList<string> States {get;}
}
Also in shared code, I have a standard base type to implement INotifyPropertyChanged more easily.
public abstract class NotifyDtoBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, IEqualityComparer<T> comparer = null, [CallerMemberName] string propertyName = null)
{
comparer = comparer ?? EqualityComparer<T>.Default;
if (comparer.Equals(field, value))
{
return false;
}
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
Then the actual OptionsCache looks like
public class OptionsCache : NotifyDtoBase, IOptionsCache
{
protected IList<string> _states;
public IList<string> States
{
get { return this._states; }
set { SetField(ref this._states, value); }
}
public async Task PopulateCacheAsync()
{
// TODO: fetch options from server
// for now, populate inline
this.States = new List<string>(){ "MI", "FL", "ME", ... }
}
}
These are working just fine. So, in my Activity, I new up an options class, and try and populate a drop down, but things go very wrong.
[Activity (Label = "Simple App", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected IOptionsCache OptionsCache;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// new OptionsCache has no options to start with
// need to call PopulateCache to get data
var options = new OptionsCache();
// When the list is populated, populate the spinners
options.PropertyChanged += (sender, args) => PopulateSpinners();
// HERE IS WHERE THINGS TO BAD!
// As I step thru the code, when I hit this line (pre-execution) and then F10 to step over, it drops into the PopulateSpinners method and this.OptionsCache == null
this.OptionsCache = options;
// populate the cache async and let the property changed event
// populate the spinners
options.PopulateCacheAsync();
}
protected void PopulateSpinners()
{
Spinner statesSpinner = FindViewById<Spinner>(Resource.Id.StatesSpinner);
// this.OptionsCache == null
ArrayAdapter<string> departureAdapter = new ArrayAdapter<string>(this, global::Android.Resource.Layout.SimpleSpinnerDropDownItem, this.OptionsCache.States.ToArray());
statesSpinner.Adapter = departureAdapter;
}
}
It seems like my assignment call to the class variable is being skipped and the next method is being invoked. Not sure if it has to do with being an async method or what's going on here...
Well, the good news is that the code does actually run correctly... when it is actually deployed to the emulator.
It would seem that the latest code does not always deploy to the emulator and you may end up debugging 'old' code. One way to tell this is happening, is that the debugger will indicate invalid lines as the next statement (eg, it may say that a blank line or a class definition is the next statement, which is obviously not correct).
https://forums.xamarin.com/discussion/45327/newest-version-of-code-not-always-deployed-when-debugging-from-xamarin-studio
I am using a singleton for fetching data from a web service and storing the resulting data object in an ArrayList. It looks like this:
public class DataHelper {
private static DataHelper instance = null;
private List<CustomClass> data = null;
protected DataHelper() {
data = new ArrayList<>();
}
public synchronized static DataHelper getInstance() {
if(instance == null) {
instance = new DataHelper();
}
return instance;
}
public void fetchData(){
BackendlessDataQuery query = new BackendlessDataQuery();
QueryOptions options = new QueryOptions();
options.setSortBy(Arrays.asList("street"));
query.setQueryOptions(options);
CustomClass.findAsync(query, new AsyncCallback<BackendlessCollection<CustomClass>>() {
#Override
public void handleResponse(BackendlessCollection<CustomClass> response) {
int size = response.getCurrentPage().size();
if (size > 0) {
addData(response.getData());
response.nextPage(this);
} else {
EventBus.getDefault().post(new FetchedDataEvent(data));
}
}
#Override
public void handleFault(BackendlessFault fault) {
EventBus.getDefault().post(new BackendlessFaultEvent(fault));
}
});
}
public List<CustomClass> getData(){
return this.data;
}
public void setData(List<CustomClass> data){
this.data = data;
}
public void addData(List<Poster> data){
this.data.addAll(data);
}
public List<CustomClass> getData(FilterEnum filter){
if(filter == FilterEnum.NOFILTER){
return getData();
}else{
// Filtering and returning filtered data
}
return getData();
}
}
The data is fetched correctly and the list actually contains data after it. Also, only one instance is created, as intended. However, whenever I call getData later, the length of this.data is 0. Because of this I also tried it with a subclass of Application holding the DataHelper object, resulting in the same problem.
Is there a good way of debugging this? Is there something like global watches in Android Studio?
Is there something wrong with my approach? Is there a better approach? I am mainly an iOS developer, so Android is pretty new to me. I am showing the data from the ArrayList in different views, thus I want to have it present in an the ArrayList as long as the application runs.
Thanks!
EDIT: Example use in a list view fragment (only relevant parts):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filter = FilterEnum.NOFILTER;
data = DataHelper.getInstance().getData(filter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
customClassListAdapter = new customClassListAdapter(getActivity(), data);}
EDIT2: Added code where I fetch the data from Backendless, changed reference of DataHelper to reference of data in first EDIT
EDIT3: I usa a local EventBus for notifying the list view about the new data. This looks like this and works (initially the data gets populated, but after e.g. applying a filter, the ArrayList I get with getData is empty):
#Subscribe
public void onMessageEvent(FetchedDataEvent event) {
customClassListAdapter.notifyDataSetChanged();
}
Try instead of keeping reference to your DataHelper instance, keeping reference to your list of retrieved items. F.e. when you first fetch the list (and it's ok as you say), assign it to a class member. Or itarate through it and create your own array list of objects for future use.
Okay I finally found the problem. It was not about the object or memory management at all. Since I give the reference on getData to my ArrayAdapter, whenever I call clear (which I do when changing the filter) on the ArrayAdapter, it empties the reference. I basically had to create a copy of the result for the ArrayAdapter:
data = new ArrayList<>(DataHelper.getInstance().getData(filter));
I was not aware of the fact that this is a reference at all. So with this the data always stays in the helper entirely. I only did this because this:
customClassListAdapter.notifyDataSetChanged();
does hot help here, it does not call getData with the new filter again.
Thanks everyone for your contributions, you definitely helped me to debug this.
It is likely that getData does get called before the data is filled.
A simple way to debug this is to add (import android.util.Log) Log.i("MyApp.MyClass.MyMethod", "I am here now"); entries to strategic places in fetchData, addData and getData and then, from the logs displayed by adb logcat ensure the data is filled before getData gets called.