【问题标题】:How to update a fragment from another class that isn't an fragment如何从另一个不是片段的类更新片段
【发布时间】:2015-05-31 19:50:42
【问题描述】:

我是 android 编程的初学者,如果这个问题看起来很愚蠢,我很抱歉,但我需要了解如何从一个不是活动或片段的类中更新视图。我创建了一个从 Google Play 服务 API 获取数据的类。我需要将此数据重定向到片段。实现它的常用软件设计模式有哪些?

这是代码,但不幸的是它不起作用

TodayFragment

package com.salvo.weather.android.fragment;


import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.salvo.weather.android.R;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
import com.salvo.weather.android.geolocation.CurrentGeolocation;

/**
 * A simple {@link Fragment} subclass.
 */
public class TodayFragment extends Fragment {

    private static final String TAG = TodayFragment.class.getSimpleName();

    private CurrentGeolocation mCurrentGeolocation;

    public TodayFragment() {
        // Required empty public constructor
    }

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

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_today, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCurrentGeolocation = CurrentGeolocation.get(getActivity());
    }

    @Override
    public void onStart() {
        super.onStart();
        mCurrentGeolocation.getmGoogleApiClient().connect();

        renderView();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.stopLocationUpdates();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.startLocationUpdates();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.stopLocationUpdates();
        }
    }

    public void renderView() {
        // check if googleApiClient is connected
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.getmCurrentWeatherRequest().loadData(new VolleyCallback() {
                @Override
                public void onSuccess(CurrentWeatherEntity currentWeatherEntity) {
                    Log.i(TAG, currentWeatherEntity.getmCity());
                }
            });

        }
    }
}

当前地理位置

package com.salvo.weather.android.geolocation;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.client.request.CurrentWeatherRequest;
import com.salvo.weather.android.entity.CurrentGeolocationEntity;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
/**
 * Created by mazzy on 30/05/15.
 */
public class CurrentGeolocation
        implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    private static final String TAG = CurrentGeolocation.class.getSimpleName();
    // SETTING CONSTANTS FOR THE LOCATION
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; //ms
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    private static CurrentGeolocation sCurrentGeolocation;
    private boolean mRequestingLocationUpdates;
    private Context mAppContext;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private CurrentGeolocationEntity mCurrentGeolocationEntity;
    private CurrentWeatherRequest mCurrentWeatherRequest;
    public static CurrentGeolocation get(Context appContext) {
        if (sCurrentGeolocation == null) {
            sCurrentGeolocation = new CurrentGeolocation(appContext.getApplicationContext());
        }
        return sCurrentGeolocation;
    }
    private CurrentGeolocation(Context appContext) {
        mAppContext = appContext;
        mRequestingLocationUpdates = true;
        mCurrentGeolocationEntity = new CurrentGeolocationEntity();
        mCurrentWeatherRequest = CurrentWeatherRequest.get(appContext);
        buildGoogleApiClient();
    }
    @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "Connected to GoggleApiClient");
        if (mCurrentGeolocationEntity.getmLastLocation() == null) {
            mCurrentGeolocationEntity.setmLastLocation(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));
            mCurrentWeatherRequest.setmCurrentGeolocationEntity(mCurrentGeolocationEntity);
        }
        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }
    @Override
    public void onConnectionSuspended(int i) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: error " + connectionResult.getErrorCode());
    }
    @Override
    public void onLocationChanged(Location location) {
        // update the location
        mCurrentGeolocationEntity.setmLastLocation(location);
    }
    public GoogleApiClient getmGoogleApiClient() {
        return mGoogleApiClient;
    }
    public void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    public void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
    public CurrentWeatherRequest getmCurrentWeatherRequest() {
        return mCurrentWeatherRequest;
    }
    private synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building Google Api Client");
        mGoogleApiClient = new GoogleApiClient.Builder(mAppContext)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }
    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
}

【问题讨论】:

  • 如果我没记错的话,你想把从父类得到的数据设置成你与父类关联的片段?
  • 没有。实际上片段和类之间没有关联。我从 Google Play 服务 API 获取数据,然后将这些数据设置为片段
  • 您有一个类,您可以在其中从 google play 服务获取数据并将该数据设置为片段,您实际上需要一个活动类来创建片段。您是从哪个活动类创建片段的?分享您的代码可能会有所帮助,因为您的问题太宽泛而无法回答。
  • @VikramEzhil 我已经发布了我的代码,但它不起作用,因为当它尝试在 google play service api get data 之前获取数据时

标签: android design-patterns android-fragments


【解决方案1】:

您必须创建一个Listener

今日片段

package com.salvo.weather.android.fragment;


import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.salvo.weather.android.R;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
import com.salvo.weather.android.geolocation.CurrentGeolocation;

/**
 * A simple {@link Fragment} subclass.
 */
public class TodayFragment extends Fragment implements CurrentGeoloaction.OnUpdateListener {

    private static final String TAG = TodayFragment.class.getSimpleName();

    private CurrentGeolocation mCurrentGeolocation;

    public TodayFragment() {
        // Required empty public constructor
    }

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

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_today, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCurrentGeolocation = CurrentGeolocation.get(getActivity());
        mCurrentGeolocation.setOnUpdateListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        mCurrentGeolocation.getmGoogleApiClient().connect();

        renderView();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.stopLocationUpdates();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.startLocationUpdates();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.stopLocationUpdates();
        }
    }

    @Override
    public void onUpdate() {
        renderView();
    }

    public void renderView() {
        // check if googleApiClient is connected
        if (mCurrentGeolocation.getmGoogleApiClient().isConnected()) {
            mCurrentGeolocation.getmCurrentWeatherRequest().loadData(new VolleyCallback() {
                @Override
                public void onSuccess(CurrentWeatherEntity currentWeatherEntity) {
                    Log.i(TAG, currentWeatherEntity.getmCity());
                }
            });

        }
    }
}

当前地理位置

package com.salvo.weather.android.geolocation;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.salvo.weather.android.app.VolleyCallback;
import com.salvo.weather.android.client.request.CurrentWeatherRequest;
import com.salvo.weather.android.entity.CurrentGeolocationEntity;
import com.salvo.weather.android.entity.CurrentWeatherEntity;
/**
 * Created by mazzy on 30/05/15.
 */
public class CurrentGeolocation
        implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    private static final String TAG = CurrentGeolocation.class.getSimpleName();
    // SETTING CONSTANTS FOR THE LOCATION
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; //ms
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    private static CurrentGeolocation sCurrentGeolocation;
    private boolean mRequestingLocationUpdates;
    private Context mAppContext;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private CurrentGeolocationEntity mCurrentGeolocationEntity;
    private CurrentWeatherRequest mCurrentWeatherRequest;
    private OnUpdateListener mOnUpdateListener;

    public interface OnUpdateListener {
        public void onUpdate();
    }

    public void setOnUpdateListener(Fragment todayFragment) {
        this.mOnUpdateListener = (OnUpdateListener) todayFragment;
    }

    public static CurrentGeolocation get(Context appContext) {
        if (sCurrentGeolocation == null) {
            sCurrentGeolocation = new CurrentGeolocation(appContext.getApplicationContext());
        }
        return sCurrentGeolocation;
    }
    private CurrentGeolocation(Context appContext) {
        mAppContext = appContext;
        mRequestingLocationUpdates = true;
        mCurrentGeolocationEntity = new CurrentGeolocationEntity();
        mCurrentWeatherRequest = CurrentWeatherRequest.get(appContext);
        buildGoogleApiClient();
    }
    @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "Connected to GoggleApiClient");
        if (mCurrentGeolocationEntity.getmLastLocation() == null) {
            mCurrentGeolocationEntity.setmLastLocation(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));
            mCurrentWeatherRequest.setmCurrentGeolocationEntity(mCurrentGeolocationEntity);
        }
        if (mRequestingLocationUpdates) {
            startLocationUpdates();
            mOnUpdateListener.onUpdate();
        }
    }
    @Override
    public void onConnectionSuspended(int i) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: error " + connectionResult.getErrorCode());
    }
    @Override
    public void onLocationChanged(Location location) {
        // update the location
        mCurrentGeolocationEntity.setmLastLocation(location);
    }
    public GoogleApiClient getmGoogleApiClient() {
        return mGoogleApiClient;
    }
    public void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    public void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
    public CurrentWeatherRequest getmCurrentWeatherRequest() {
        return mCurrentWeatherRequest;
    }
    private synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building Google Api Client");
        mGoogleApiClient = new GoogleApiClient.Builder(mAppContext)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }
    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
}

【讨论】:

  • 谢谢。这是正确的以下答案所说stackoverflow.com/questions/27844512/…
  • 您要将哪些数据重定向到 TodayFragment?
  • 工作流程如下:应用程序启动,从 google play services api 获取数据,然后将此数据存储到mCurrentGeolocationEntity 将其传递给mCurrentWeatherRequest 实例,然后调用函数@ 987654327@从服务器获取数据
  • 无论如何你给了我一个好主意。如果可行,我会发布结果
  • 你想在startLocationUpdates之后调用renderView吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多