How should I call the function QueryUtils.fetchData(REQUEST_URL
) inside of ViewModel
, it returns List<Earthquakes>
. This code fetches data the way it should, but it doesn't display it probably because it already sets data before it is fetched.
public class MainActivity extends AppCompatActivity {
private EarthquakeAdapter mEarthquakeAdapter;
private EarthquakeViewModel aEarthquakeViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Redacted
aEarthquakeModel = ViewModelProviders.of(this).get(EarthquakeViewModel.class);
aEarthquakeViewModel.fetchEarthquakes().observe(this, new Observer<ArrayList<Earthquake>>() {
@Override
public void onChanged(ArrayList<Earthquake> earthquakes) {
if(earthquakes != null) {
mEarthquakeAdapter.clear();
mEarthquakeAdapter.addAll(earthquakes);
}
}
});
}
}
public class EarthquakeViewModel extends AndroidViewModel {
public MutableLiveData<ArrayList<Earthquake>> earthquakesData;
private ArrayList<Earthquake> earthquakes;
public EarthquakeViewModel(@NonNull Application application) {
super(application);
Log.i("EarthquakeViewModel", "EarthquakeViewModel constructor entered");
earthquakesData = new MutableLiveData<>();
doIt();
Log.i("EarthquakeViewModel", "EarthquakeViewModel constructor finished");
}
public LiveData<ArrayList<Earthquake>> fetchEarthquakes() {
earthquakesData.setValue(earthquakes);
return earthquakesData;
}
public void doIt() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
earthquakes = (ArrayList<Earthquake>) QueryUtils.fetchData(REQUEST_URL);
}
});
thread.start();
}
}