返回对象的问题来自扩展AsyncTask的类

时间:2019-06-21 13:18:44

标签: java android android-fragments android-asynctask return

我在使用getter函数从扩展AsyncTask的HttpRequestCurrentWeather类返回对象时遇到问题。在此类中,我从API接收数据,并希望根据收到的内容在CurrentWeatherFragment中设置一些TextView。问题是我无法将DataModel的整个对象返回到Fragment并在那里设置组件,也无法将TextViews设置为onPostExecute()方法,因为我得到了NullPointerException(java.lang.NullPointerException:尝试调用虚拟方法' android.view.View android.view.View.findViewById(int)'上的null对象引用)。我应该怎么设置那些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;
    }
}

0 个答案:

没有答案