片段事务

时间:2015-08-31 16:40:45

标签: android android-fragments

我和这个人打了一个星期,没有运气。

从一开始:

包含导航抽屉的活动。这项活动有自己的片段。片段具有向天气api发送请求的逻辑和用给定数据更新自身的逻辑。在第一次运行似乎一切正常!我能够使用给定的数据发送请求和填充视图(使用okHttp)。

片段重新播放后,一切都开始崩溃,我不断将getActivity()变为null;(

以下代码示例:

碎片首次初始化:

public abstract class DoubleFragmentActivity extends AppCompatActivity {
    protected static final String TOP_FRAGMENT = "TOP_FRAGMENT";
    protected static final String BOTTOM_FRAGMENT = "BOTTOM_FRAGMENT";
    protected abstract Fragment topFragment();
    protected abstract Fragment bottomFragment();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_container);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.topFragmentContainer, topFragment(), TOP_FRAGMENT)
                    .add(R.id.bottomFragmentContainer, bottomFragment(), BOTTOM_FRAGMENT)
                    .commit();
            getSupportFragmentManager().executePendingTransactions();
        }
    }
}

导航抽屉:

 private void selectDrawerItem(MenuItem menuItem) {
        Fragment f;
        Fragment f2;

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        switch (menuItem.getItemId()) {
            case R.id.forecastFragment:
                f = getSupportFragmentManager().findFragmentByTag("TOP_FRAGMENT");
                f2 = getSupportFragmentManager().findFragmentByTag("BOTTOM_FRAGMENT");
                if (f != mCurrentForecastFragment || f2 != mDailyForecastFragment) {
                    ft.replace(R.id.topFragmentContainer, new CurrentForecastFragment(), "TOP_FRAGMENT");
                    ft.replace(R.id.bottomFragmentContainer, new DailyForecastFragment(), "BOTTOM_FRAGMENT");
                } else {

                }
               break;
            case R.id.settingsFragment:
                mToolbar.setVisibility(View.INVISIBLE);
                f = new SettingsFragment();
                ft.replace(R.id.topFragmentContainer, f);
                break;
            case R.id.paymentsFragment:
                f = new PaymentsFragment();
                ft.replace(R.id.topFragmentContainer, f);
                break;
            case R.id.aboutFragment:
                break;
            default:
        }
        getSupportFragmentManager().executePendingTransactions();
        ft.commit();

        menuItem.setChecked(true);
        setTitle(menuItem.getTitle());
        mDrawer.closeDrawers();
        }

用于连接和填充数据的片段逻辑:

public void makeConnectionToApi(String lat, String lon) {
       mWeatherParams.setLanguage(Locale.getDefault().getLanguage());
        Activity a = getActivity();

        Uri.Builder currentBuilder = new Uri.Builder();
        currentBuilder.scheme("http")
                .authority("api.openweathermap.org")
                .appendPath("data")
                .appendPath("2.5")
                .appendPath("weather")
                .appendQueryParameter(WeatherConstants.KEY_LATITUDE, lat)
                .appendQueryParameter(WeatherConstants.KEY_LONGITUDE, lon)
                .appendQueryParameter(WeatherConstants.KEY_UNITS, mUnit)
                .appendQueryParameter(WeatherConstants.KEY_LANGUAGE, mWeatherParams.getLanguage())
                .appendQueryParameter("APPID", "###");

        String currentUrl = currentBuilder.build().toString();
        if (mUtility.isNetworkAvalaible()) {
            Request requestCurrent = new Request.Builder().url(currentUrl).build();


            //FIRST CALL
            mCall = client.newCall(requestCurrent);
            mCall.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                    Bundle args = new Bundle();
                    args.putString(TAG, e.toString());
                    Utility.invokeDialog(TAG, e.toString(), getFragmentManager());
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    String responseBody = String.valueOf(response.body().string());
                    try {
                        mForecast.setCurrent(fetchCurrent(responseBody));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            fillViewWithValues();

                        }
                    });
                }
            });


        } else {
            Utility.invokeDialog(TAG, "Check your internet connection!", getFragmentManager());
        }
    }


    private Current fetchCurrent(String responseBody) throws JSONException {
        Current current = new Current();

        JSONObject jo = new JSONObject(responseBody);

        //FETCH WEATHER ARRAY
        JSONArray weather = jo.getJSONArray(WeatherConstants.KEY_CURRENT_CONDITIONS_ARRAY);
        for (int j = 0; j < weather.length(); j++) {
            JSONObject weatherParser = weather.getJSONObject(j);
            current.setIcon(weatherParser.getString(WeatherConstants.KEY_ICON_ID));
            Log.i(TAG, "Icons ID: " + weatherParser.getString(WeatherConstants.KEY_ICON_ID));
            current.setConditions(weatherParser.getString(WeatherConstants.KEY_DESCRIPTION));
        }

        //FETCH TEMP
        JSONObject temp = jo.getJSONObject(WeatherConstants.KEY_MAIN_OBJECT);
        current.setDay(temp.getDouble(WeatherConstants.KEY_TEMP));
        current.setPressure(temp.getDouble(WeatherConstants.KEY_PRESSURE));
        current.setHumidity(temp.getDouble(WeatherConstants.KEY_HUMIDITY));
        current.setDayMax(temp.getDouble(WeatherConstants.KEY_TEMP_DAY_MAX));

//        FETCH VISIBILITY
        if (jo.has(WeatherConstants.KEY_VISIBILITY)) {
            current.setVisibility(jo.getInt(WeatherConstants.KEY_VISIBILITY));
        }

        //FETCH WIND

        JSONObject wind = jo.getJSONObject(WeatherConstants.KEY_WIND_OBJECT);
        current.setWindSpeed(wind.getDouble(WeatherConstants.KEY_WIND_SPEED));
        if (wind.has(WeatherConstants.KEY_WIND_DEGREES)) {
            current.setWindDegrees(wind.getInt(WeatherConstants.KEY_WIND_DEGREES));
        }


        JSONObject clouds = jo.getJSONObject(WeatherConstants.KEY_CLOUDS);
        current.setClouds(clouds.getInt("all"));
        current.setTimeStamp(jo.getInt(WeatherConstants.KEY_TIMESTAMP));
        current.setCurrentLocation(jo.getString(WeatherConstants.KEY_CITY_NAME));

        return current;
    }

    private void fillViewWithValues() {
        Current current = mForecast.getCurrent();
        if (mDeegreSwitch == 0) {
            mCurrentTemperature.setText(current.getDay() + "\u00B0");
//            setBackgroundColor(current.getDay());
        } else {
            int c = current.getDay();
            double f = (9.0 / 5.0) * c + 32;
            int e = (int) Math.round(f);

            mCurrentTemperature.setText(String.valueOf((int) Math.round(f)) + "\u00B0");
//            setBackgroundColor(e);
        }

        mCurrentCondition.setText(current.getConditions());
        mPressure.setText(String.valueOf(current.getPressure()) + "hPa");
        mClouds.setText(String.valueOf(current.getClouds()) + "%");
        mHumidity.setText(String.valueOf(current.getHumidity()) + "%");

        mCurrentIcon.setImageResource(current.getIcon());

    }

此处出现问题:getConnectionToApi方法中的getActivity()。runOnUiThread。我试图从onAttach方法获取一个活动,并将其作为参数传递给makeConnectionToApi,但它有效...但部分。应用程序没有崩溃,但片段的视图没有更新,就像下面有第二个片段或者什么。

我填写它可能是线程的东西,或者我对片段事务做错了......

0 个答案:

没有答案