Проблема с возвратом объекта из класса, расширяющего AsyncTask - PullRequest
1 голос
/ 21 июня 2019

У меня проблема с функцией получения, возвращающей объект из класса HttpRequestCurrentWeather, расширяющего AsyncTask.В этом классе я получаю данные из API и хочу установить несколько TextViews в CurrentWeatherFragment в зависимости от того, что я получил.Проблема в том, что я не могу вернуть весь объект DataModel во фрагмент и установить там компоненты, а также установить TextViews для метода onPostExecute (), потому что я получаю исключение NullPointerException (java.lang.NullPointerException: попытка вызвать виртуальный метод »android.view.View android.view.View.findViewById (int) 'для пустой ссылки на объект).Что я должен сделать, чтобы установить эти TextViews?

public class CurrentWeatherFragment extends Fragment {
    DataModel dataModel = new DataModel();

    TextView tv_city;
    TextView tv_temperature;
    TextView tv_pressure;

    public void setComponents() {
        this.tv_city = getView().findViewById(R.id.tv_current_city_name);
        tv_city.setText(dataModel.getName());

        this.tv_temperature = getView().findViewById(R.id.tv_current_temperature);
        tv_temperature.setText(dataModel.getTemp());

        this.tv_pressure = getView().findViewById(R.id.tv_current_pressure);
        tv_pressure.setText(dataModel.getPressure());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View RootView = inflater.inflate(R.layout.fragment_current_weather_layout, container, false);


        HttpRequestCurrentWeather httpRequestCurrentWeather1 = new HttpRequestCurrentWeather();
        httpRequestCurrentWeather1.execute("", "", "");

        // here I receive null object, but why?
        dataModel = httpRequestCurrentWeather1.getDataModel();

        // set the texts in components:
        setComponents();

        return RootView;
    }
}
public class HttpRequestCurrentWeather extends AsyncTask<String, Void, DataModel> {
        DataModel dataModel;

        public HttpRequestCurrentWeather() {
            this.dataModel = null;
        }

        @Override
        protected DataModel doInBackground(String... params) {
            ApiCurrentWeather apiCurrentWeather1 = new ApiCurrentWeather("London", "uk");

            try {
                // catch the model with recived data from API:
                dataModel = apiCurrentWeather1.getWeather();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return dataModel;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(DataModel dataModel) {
        super.onPostExecute(dataModel);

        CurrentWeatherFragment fragment = new CurrentWeatherFragment();

        TextView tv_temperature = (TextView)fragment.getView().findViewById(R.id.tv_current_temperature);
        tv_temperature.setText(dataModel.getTemp());

    }

    // this function returns NULL object ????
    public DataModel getDataModel(){
        return this.dataModel;
    }
}
...