片段方向



>我使用openweathermap api并成功检索了温度,城市名称,天气图标等json数据。但是,当我旋转屏幕时,网络服务再次运行,这不应该发生。

我所做的是以下几点。我保存状态或片段。

public class MainActivity extends AppCompatActivity implements  
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks{
private static final int PLAY_SERVICES_CODE = 90;
GoogleApiClient googleApiClient;
private static final String TAG = "Location";
private static final String TODAY_FRAGMENT = "today_fragment";
public static double lat = 0;
public static double log = 0;
TodayForecast ff;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FragmentManager fragmentManager = getSupportFragmentManager();
    ff = (TodayForecast) fragmentManager.findFragmentByTag(TODAY_FRAGMENT);
    if (savedInstanceState != null) {
        //Restore the fragment's instance
        ff = (TodayForecast) 
     getSupportFragmentManager().getFragment(savedInstanceState,   
     "mContent");
    }

    if(checkPlayServices()){
        initializeGoogleApiClient();
    }
}
private void initializeGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addOnConnectionFailedListener(this)
            .addConnectionCallbacks(this)
            .build();
}
public boolean checkPlayServices(){
    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
    if(result!= ConnectionResult.SUCCESS){
        if(GooglePlayServicesUtil.isUserRecoverableError(result)){
            GooglePlayServicesUtil.getErrorDialog(result, this, PLAY_SERVICES_CODE).show();
        }
        return false;
    }
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Location loc = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    if(loc!=null){
        //Log.v(TAG,"lat: "+lat);
        //Log.v(TAG,"lon: "+log);
        if(ff == null) {
            lat = loc.getLatitude();
            log = loc.getLongitude();
            ff = new TodayForecast();

 getSupportFragmentManager().beginTransaction().replace(R.id.main_container,  
 TodayForecast.newInstance(lat,log),TODAY_FRAGMENT).commit();
        }
    }else{
        Toast.makeText(getApplicationContext(),"No location 
        obtained",Toast.LENGTH_SHORT).show();
    }
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}
@Override
protected void onStop() {
    super.onStop();
    if(googleApiClient.isConnected()){
        googleApiClient.disconnect();
    }
  }
 }

在实际片段中,我使用 onSaveInstanceState 方法来存储从我的 Web 服务检索到的数据。这是整个片段的代码。

public class TodayForecast extends Fragment {
private static  String NEW_BASE_URL = "" ;
public static String URL= "http://api.openweathermap.org/data/2.5/weather?";
public static String NEW_URL= "http://api.openweathermap.org/data/2.5/weather?q=";
public static String BASE_URL= "";
public String time;
public String setTime;
String IMG_URL = "http://api.openweathermap.org/img/w/";
static double mlat;
static double mlot;
TextView cityText;
ImageView imageView;
private String cityName;
private String humidity;
private String pressure;
private String speed;
private String imageIcon;
private String temperature;
TextView tempTextView;
TextView windTextView;
TextView pressureTextView;
TextView humidityTextView;
TextView sunriseTextView;
TextView sunSetTextView;
Button btn;
private String icon;
public static TodayForecast newInstance(double lat, double log) {
    TodayForecast fragment = new TodayForecast();
    mlat = lat;
    mlot = log;
    return fragment;
}
public TodayForecast() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_today_forecast, container, false);
    Log.v("Theo","lot: " + mlot);
    Log.v("Theo","lat: " + mlat);
    cityText = (TextView)rootView.findViewById(R.id.cityText);
    imageView = (ImageView) rootView.findViewById(R.id.thumbnailIcon);
    windTextView = (TextView) rootView.findViewById(R.id.windTextValue);
    tempTextView = (TextView)rootView.findViewById(R.id.tempText);
    pressureTextView = (TextView)rootView.findViewById(R.id.pressureTextValue);
    humidityTextView = (TextView)rootView.findViewById(R.id.humidTextValue);
    sunriseTextView = (TextView)rootView.findViewById(R.id.riseTextValue);
    sunSetTextView = (TextView)rootView.findViewById(R.id.setTextValue);
    btn = (Button)rootView.findViewById(R.id.change_city);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //showInputDialog();


        }
    });
    //http://api.openweathermap.org/data/2.5/weather?lat=39.6304951&lon=22.4206619&appid=d48708e1e4d8e2b60da14778acd8d56a
    BASE_URL = URL +"lat="+mlat+"&lon="+mlot+"&units=metric&appid=d48708e1e4d8e2b60da14778acd8d56a";
    if(savedInstanceState!=null) {
        String city_name = savedInstanceState.getString("CityName");
        String city_temp = savedInstanceState.getString("CityTemp");
        String city_pressure = savedInstanceState.getString("CityPressure");
        String city_humidity = savedInstanceState.getString("CityHumidity");
        String wind_speed = savedInstanceState.getString("WindSpeed");
        String weather_icon = savedInstanceState.getString("weatherIcon");
        String sunrise_time = savedInstanceState.getString("sunrise");
        String sunset_time = savedInstanceState.getString("sunset");

        cityText.setText(city_name);
        tempTextView.setText(city_temp);
        pressureTextView.setText(city_pressure);
        humidityTextView.setText(city_humidity);
        windTextView.setText(wind_speed);

        Picasso.with(getActivity()).load(weather_icon).into(imageView);
        sunriseTextView.setText(sunrise_time);
        sunSetTextView.setText(sunset_time);

    }else{
      weatherData();
    }
    //http://api.openweathermap.org/data/2.5/weather?q=Newcastle,uk&units=metric&appid=d48708e1e4d8e2b60da14778acd8d56a

    return rootView;

}

private void weatherData() {
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            BASE_URL,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("TAG", response.toString());
                    try {
                        cityName = response.getString("name");
                        cityText.setText(cityName);
                        //cityTextView.setText(cityName);
                        JSONObject main = response.getJSONObject("main");
                        temperature = main.getString("temp");
                        //String temperatureSbstr = temperature.substring(0, 2);
                        tempTextView.setText(temperature+""+"u00b0 u0043");
                        humidity = main.getString("humidity");
                        humidityTextView.setText(humidity + " %");
                        pressure = main.getString("pressure");
                        pressureTextView.setText(pressure + " hPa");
                        JSONObject windValue = response.getJSONObject("wind");
                        speed = windValue.getString("speed");
                        windTextView.setText(speed + " km/h");
                        JSONObject sysJSONObject = response.getJSONObject("sys");
                        long sunrise = sysJSONObject.getLong("sunrise");
                        Date dayTime = new Date(sunrise * 1000L);
                        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                        time = timeFormat.format(dayTime);
                        sunriseTextView.setText(time);
                        long sunset = sysJSONObject.getLong("sunset");
                        Date sunsetTime = new Date(sunset * 1000L);
                        SimpleDateFormat sunsettimeFormat = new SimpleDateFormat("HH:mm:ss");
                        setTime = sunsettimeFormat.format(sunsetTime);
                        sunSetTextView.setText(setTime);
                        JSONArray weather = response.getJSONArray("weather");
                        for(int i=0; i<weather.length();i++){
                            JSONObject weatherJSONObject = weather.getJSONObject(i);
                            String mainWeather = weatherJSONObject.getString("main");
                            //mainText.setText(mainWeather);
                            icon = weatherJSONObject.getString("icon");
                            //Volley's Image request
                            ImageLoader imageLoader = AppController.getInstance().getImageLoader();
                            imageIcon = IMG_URL + icon;
                            imageLoader.get(imageIcon, new ImageLoader.ImageListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                }
                                @Override
                                public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                                    if (response.getBitmap() != null) {
                                        // load image into imageview
                                        imageView.setImageBitmap(response.getBitmap());
                                    }
                                }
                            });
                            Log.d("icon", icon);
                        }
                    } catch (JSONException e) {
                        Log.e("TAG", e.toString());
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}


@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("CityName",cityName);
    outState.putString("CityTemp",temperature);
    outState.putString("CityPressure",pressure);
    outState.putString("CityHumidity",humidity);
    outState.putString("WindSpeed",speed);
    outState.putString("sunrise",time);
    outState.putString("sunset",setTime);
    outState.putString("weatherIcon",imageIcon);

}

}

您会看到,在存储检索到的数据后,当捆绑对象(即保存实例状态引用)不为空时,我在onCreateView(...)方法中读取它们。如果它为 null 表示没有屏幕旋转,则 Web 服务正在运行。

当我必须使用 Parceable 对象在回收器视图中显示数据时,我修复了这个问题。

任何想法,

谢谢!

如果系统稍后必须重新创建活动实例,它将相同的 Bundle 对象传递给 onRestoreInstanceState() 和 onCreate() 方法。因此,您可以使用这两种方法中的任何一种检索数据。我还没有测试解决方案。这是根据 https://developer.android.com/training/basics/activity-lifecycle/recreating.html。

最新更新