Tabarek Ghassan
Tabarek Ghassan

Reputation: 806

show last known weather state with no Internet connection

I build a weather app using java and android studio I used openweathermap API to return weather data

also, I used Retrofit library to do that

what I want is that when there's no internet connection I want to display the latest weather state instead of a progress bar in the page

can you help me, please?

my weather fragment class code is this

public class TodayWeatherFragment extends Fragment {


    ImageView img_weather;
    TextView txt_city_name, txt_temp, txt_discription, txt_date_time, txt_wind,txt_pressure , txt_humiditty,
            txt_sunrise,txt_sunset, txt_geo_coords;
    LinearLayout weather_panel;
    ProgressBar loading;


    CompositeDisposable compositeDisposable;
    IOpenWeatherClass mService ;


    static TodayWeatherFragment instance;

    public static TodayWeatherFragment getInstance() {
        if(instance == null)
            instance = new TodayWeatherFragment();
        return instance;
    }

    public TodayWeatherFragment() {

        compositeDisposable = new CompositeDisposable();
        Retrofit retrofit =  RetrofitClient.getInstance();

        mService=retrofit.create(IOpenWeatherClass.class);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View itemView = inflater.inflate(R.layout.fragment_today_weather, container, false);

        img_weather = (ImageView) itemView.findViewById(R.id.img_weather);
        txt_city_name = (TextView) itemView.findViewById(R.id.txt_city_name);
        txt_temp = (TextView) itemView.findViewById(R.id.txt_temp);
        txt_discription = (TextView) itemView.findViewById(R.id.txt_discription);
        txt_date_time = (TextView) itemView.findViewById(R.id.txt_date_time);
        txt_wind = (TextView) itemView.findViewById(R.id.txt_wind);
        txt_pressure = (TextView) itemView.findViewById(R.id.txt_pressure);
        txt_humiditty = (TextView) itemView.findViewById(R.id.txt_humiditty);
        txt_sunrise = (TextView) itemView.findViewById(R.id.txt_sunrise);
        txt_sunset = (TextView) itemView.findViewById(R.id.txt_sunset);
        txt_geo_coords = (TextView) itemView.findViewById(R.id.txt_geo_coords);

        weather_panel = (LinearLayout)itemView.findViewById(R.id.weather_panel);

        loading = (ProgressBar) itemView.findViewById(R.id.loading);

        getWeatherInformation();


        return itemView;
    }

    private void getWeatherInformation() {

        compositeDisposable.add(mService.getWeatherByLatLng(String.valueOf(Common.current_location.getLatitude()),
                String.valueOf(Common.current_location.getLatitude()),
                Common.APP_ID,
                "metric").subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<WeatherResult>() {
                               @Override
                               public void accept(WeatherResult weatherResult) throws Exception {

                                   //Load image
                                   Picasso.get().load(new StringBuilder("https://openweathermap.org/img/w/")
                                           .append(weatherResult.getWeather().get(0).getIcon())
                                   .append(".png").toString()).into(img_weather);


                                   //load information

                                   txt_city_name.setText(weatherResult.getName());
                                   txt_discription.setText(new StringBuilder("Weather in ")
                                   .append(weatherResult.getName()).toString());
                                   txt_temp.setText(new StringBuilder(String.valueOf(weatherResult.getMain().getTemp()))
                                   .append("C").toString());
                                   txt_date_time.setText(Common.convertUnixToDate(weatherResult.getDt()));
                                   txt_pressure.setText(new StringBuilder(String.valueOf(weatherResult.getMain().getPressure()))
                                           .append("hpa").toString());
                                   txt_humiditty.setText(new StringBuilder(String.valueOf(weatherResult.getMain().getHumidity()))
                                           .append("%").toString());
                                   txt_sunrise.setText(Common.convertUnixToHour(weatherResult.getSys().getSunrise()));
                                   txt_sunset.setText(Common.convertUnixToHour(weatherResult.getSys().getSunset()));
                                   txt_geo_coords.setText(new StringBuilder("[").append(weatherResult.getCoord().toString())
                                           .append("]").toString());

                                   //display panel

                                   weather_panel.setVisibility(View.VISIBLE);
                                   loading.setVisibility(View.GONE);






                               }

                           }, new Consumer<Throwable>() {
                               @Override
                               public void accept(Throwable throwable) throws Exception {
                                   Toast.makeText(getActivity(), ""+throwable.getMessage(), Toast.LENGTH_SHORT).show();
                               }
                           }

                )

        );
    }

}

Upvotes: 1

Views: 124

Answers (2)

Chetan Joshi
Chetan Joshi

Reputation: 5711

You should keep last known whether data to your application in any format like , File , SQLite Data Base , Shared Preference .

Because you think like Location service stored last known location Android not keep whole whether data same as Location Service.

So you should keep Whether data with your own app with time stamp so when internet is not available you can show it from your saved data by matching with current day timestamp.

Upvotes: 4

Antoine El Murr
Antoine El Murr

Reputation: 317

You can save data in sqlite and check if there is no internet connection preview the data from the database

PS: Use ROOM (it's a component created by the android dev team) it manage your Database more easily. Here is a link for the ROOM Library: https://developer.android.com/topic/libraries/architecture/room

Upvotes: 2

Related Questions