如何从不是片段的另一个类更新片段

时间:2015-05-31 19:50:43

标签: android design-patterns android-fragments

我是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());
                }
            });

        }
    }
}

CurrentGeolocation

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);
    }
}

1 个答案:

答案 0 :(得分:3)

您必须创建Listener

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 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());
                }
            });

        }
    }
}

CurrentGeolocation

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);
    }
}