2015-09-02 173 views
0

我有以下一段代码,它从openweathermap api中检索一些天气数据。 AsyncTask类用于此目的。片段旋转

public class ForecastFragment extends Fragment { 
String imageUrl; 
ListView listView; 
List<WeatherForecastData> WeatherForecastDataList; 
String IMG_URL = "http://api.openweathermap.org/img/w/"; 
Fragment fragment; 

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

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    //Inflate xml view and convert it to a View object 
    View rootView = inflater.inflate(R.layout.fragment_forecast, container, false); 

    //Initialise ListView. 
    listView = (ListView) rootView.findViewById(R.id.listView); 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      String temp = WeatherForecastDataList.get(position).getWeatherTemperature(); 

      Toast.makeText(getActivity(), temp + "° C"+" Have a nice day", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    return rootView; 
} 

//Now we are ready for further processing 
@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 

    setRetainInstance(true); 
    if (savedInstanceState == null) { 
     if(isOnline()) { 
      requestData("http://api.openweathermap.org/data/2.5/forecast/daily?lat=50.09&lon=14.42&cnt=9&&units=metric&mode=json"); 
     }else{ 
      Toast.makeText(getActivity(),"There is no internet connection",Toast.LENGTH_SHORT).show(); 
     } 
    } 

} 

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) { 
    savedInstanceState.putString("ImageURL", imageUrl); 
    super.onSaveInstanceState(savedInstanceState); 
} 

//We create a MyTask object,and execute the async. thread with the specified url which is shown just above. 
private void requestData(String uri) { 
    MyTask task = new MyTask(); 
    task.execute(uri); 
} 

//AsyncTask that will do the asynchronous threading. It displays the weather's icon,description 
//and temperature in the main thread via the OnPostExecute(...) method. 
private class MyTask extends AsyncTask<String, String, List<WeatherForecastData>> { 

    @Override 
    protected void onPreExecute() { 
     //Used to initialise Views such as Progress Bars which are not needed for this 
     //project. 
    } 

    @Override 
    protected List<WeatherForecastData> doInBackground(String... params) { 
     //Read the url,specify the METHOD GET, and store it in content. 
     String content = HttpManager.getData(params[0]); 
     //JSON parsing of the openweather api's response. It is not hard,but I had to use the 
     //debugger quite a lot to make sure that I deserialise the correct JSON values into Strings. 
     WeatherForecastDataList = WeatherJSONParser.parseFeed(content); 
     //Fetching the url image 
     for (WeatherForecastData d : WeatherForecastDataList) { 
      try { 
       imageUrl = IMG_URL + d.getPhoto(); 
       InputStream in = (InputStream) new URL(imageUrl).getContent(); 
       Bitmap bitmap = BitmapFactory.decodeStream(in); 
       //Is it deprecated? 
       d.setBitmap(bitmap); 
       in.close(); 
      } catch (Exception e) { 
       e.printStackTrace(); 

      } 
     } 
     return WeatherForecastDataList; 
    } 

    //WeatherForecastData is the Object that contains all that instances we want to display. 
    @Override 
    protected void onPostExecute(List<WeatherForecastData> result) { 

     if (result == null) { 
      Toast.makeText(getActivity(), "There is some wrong,and data can not be displayed", Toast.LENGTH_LONG).show(); 
      return; 
     } 
     WeatherForecastDataList = result; 
     //Display the ListView. 
     WeatherAdapter adapter = new WeatherAdapter(getActivity(), R.layout.weather_row, WeatherForecastDataList); 
     listView.setAdapter(adapter); 
    } 

} 

protected boolean isOnline() { 
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
     return true; 
    } else { 
     return false; 
    } 
} 
} 

我的问题是如何让我的异步任务类工作的时候手机rotates.In换句话说,我不希望我的片段被杀死你的,但是存储的天气得到我所得到的。我在这里也看到了其他一些问题,但在这一部分我很困惑。谢谢。

+0

使用'机器人:configChanges =“方向|屏幕尺寸“'属性在Menifest文件中的活动 – chandil03

+0

谢谢。有用。 – Theo

+1

做chadil03说要做的事就像当你离开的时候把你的房门放到你的房门上,然后在你回来的时候走过它。 如果你想要内存泄漏窃贼进入你的房子内,而你的钢铁和你的记忆可以随意使用这种方法。否则,请看Kaveesh Kanwal下面的答案。 – dell116

回答

6

在清单中进行配置更改是而不是保存片段实例的推荐方式。

相反,您应该将片段的实例保存在容器活动的onSaveInstanceState()覆盖方法中。 下面是一个小片段,这将有助于你:

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    getSupportFragmentManager().putFragment(outState,"fragmentInstanceSaved",getSupportFragmentManager().findFragmentById(R.id.fragment_container)); 
} 

现在,在你的容器活动的onCreate方法检查,如果包是空或不是:

if(savedInstanceState!=null){ 
      Fragment fragment = getSupportFragmentManager().getFragment(savedInstanceState,"fragmentInstanceSaved"); 
      //recreate your preserved fragment here 
     }else{ 
      //goto ur default activity or fragment.... 
} 
+1

为我工作:) –

+0

我很高兴它为你工作SK。 :) –