Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – One method get respond from WebServer and other method need answer of that method to return something , and unfortunately I got null

Posted on November 11, 2022 By

Solution 1 :

It’s because it takes a while before a response is returned.

Usually, you need a LiveData object to get results from background tasks.

In your MainActivityViewModel, add the following:

private MutableLiveData currentWeatherData = new MutableLiveData<CurrentWeather>();

public LiveData<CurrentWeather> getCurrentWeatherData() {
    return currentWeatherData;
}

When you get response, update your LiveData

currentWeather = gson.fromJson(serverResponde, CurrentWeather.class);
currentWeatherData.postValue(currentWeather);

In your activity, you need to observe this LiveData.

viewModel.getCurrentWeatherData().observe(this, new Observer<CurrentWeather>() {
        @Override
        public void onChanged(CurrentWeather c) {
           // Do whatever you want with c.
        }
    });

Problem :

In MainActivityViewModel class i have one Getter method that returns an instance of CurrentWeather (pojo class) and this method needs response from OnResponse method but I get null for first time.

The first methods invoke from MainActivity, viewModel is not null but the currentWeather instance is.

MainActivityViewModel viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
currentWeather = viewModel.getCurrentWeather();

I don’t know if I can ask to wait for a moment before return currentWeather in first method or not.

public class MainActivityViewModel extends ViewModel implements Callback<ResponseBody> {

    private CurrentWeather currentWeather;

    public CurrentWeather getCurrentWeather() {
        if (currentWeather == null) {
            createCurrentWeather("London");
        }
        return currentWeather;
    }

    public void createCurrentWeather(String city) {
        RetrofitApiManager.getInstance().getCurrentWeatherApi(this, city);
    }

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

        if (response.isSuccessful()) {
            ResponseBody body = response.body();
            try {
                String serverResponde = body.string();
                Timber.e(serverResponde);
                Gson gson = new Gson();
                currentWeather = gson.fromJson(serverResponde, CurrentWeather.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
    }
}

Comments

Comment posted by Amir Hossein

Thanks, it works with LiveData but is there other way in the first method to ask it to wait ?

Comment posted by Loremar Marabillas

@AmirHossein I can think of two ways. One is to use the synchronous call for Retrofit wherein you won’t need to override onResponse. And two, you can use CountDownLatch wherein you await until countdown is called inside onResponse. Either ways, you will be blocking the UI thread which is something that you shouldn’t do. The LiveData approach is best practice and is the recommended approach.

READ  [FIXED] android - Binding to cellular network with bindProcessToNetwork does not work
Powered by Inline Related Posts

Comment posted by Amir Hossein

thanks , I think as you Mentioned here Live Data is the best .

Android Tags:android, retrofit2, viewmodel

Post navigation

Previous Post: [FIXED] android – Convert BMP image to PNG or JPG in Java without loading the entire image in memory
Next Post: [FIXED] xml – Android – prevent TextView to push out another element inside LinearLayout

Related Posts

[FIXED] android – Flutter twitter login without firebase Android
[FIXED] android – Flutter getx ui not fully build issue on loading –release version Android
[FIXED] android – how and where to save state of recycler view in fragment Android
[FIXED] android – how to save response to room database correctly? Android
[FIXED] Errors in Android Studio unless I build/clean each time Android
[FIXED] android – Error running app. No target device found Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • Can VPN be traced by police?
  • Where were Kaiser-Frazer cars built?
  • How do you make gold rose gold paint?
  • What are the newest type of dentures?
  • Can you wear joggers as dress pants?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme