Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android如何保存状态arraylist_Java_Android_Save_Fragment_Restore - Fatal编程技术网

Java Android如何保存状态arraylist

Java Android如何保存状态arraylist,java,android,save,fragment,restore,Java,Android,Save,Fragment,Restore,我正在制作一个3个片段页面的应用程序,第一个片段从http加载json,但当我转到fragment3并返回fragment1时,它会消失,并再次从http加载。如何正确设置片段中的保存/还原状态 片段1代码: public class Fragment1 extends Fragment { private ArrayList<FeedItem> feedList = null; private ProgressBar progressbar = null;

我正在制作一个3个片段页面的应用程序,第一个片段从http加载json,但当我转到fragment3并返回fragment1时,它会消失,并再次从http加载。如何正确设置片段中的保存/还原状态

片段1代码:

    public class Fragment1 extends Fragment  {
 private ArrayList<FeedItem> feedList = null;
    private ProgressBar progressbar = null;
    private ListView feedListView = null;



  @Override  
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
      View rootView = inflater.inflate(R.layout.activity_post_list, container, false);

      progressbar = (ProgressBar)rootView.findViewById(R.id.progressBar);
      String url = "";
      new DownloadFilesTask().execute(url);
    return rootView;


  } 


  public void updateList() {
      feedListView= (ListView)getActivity().findViewById(R.id.custom_list);

      feedListView.setVisibility(View.VISIBLE);
      if (progressbar.isShown()) {
          progressbar.setVisibility(View.GONE); 
      }


      feedListView.setAdapter(new CustomListAdapter(getActivity(), feedList));
      feedListView.setOnItemClickListener(new OnItemClickListener() {



              @Override
              public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                      Object o = feedListView.getItemAtPosition(position);
                      FeedItem newsData = (FeedItem) o;


                      Intent intent = new Intent(getActivity(), FeedDetailsActivity.class);
                      intent.putExtra("feed", newsData);
                      startActivity(intent);
              }
      });
        }

       public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {

      @Override
      protected void onProgressUpdate(Integer... values) {
      }

      @Override
      protected void onPostExecute(Void result) {
              if (null != feedList) {
                      updateList();
              }
      }

      @Override
      protected Void doInBackground(String... params) {
              String url = params[0];

              // getting JSON string from URL
              JSONObject json = getJSONFromUrl(url);

              //parsing json data
              parseJson(json);
              return null;
      }
        }


       public JSONObject getJSONFromUrl(String url) {
      InputStream is = null;
      JSONObject jObj = null;
      String json = null;

      // Making HTTP request
      try {
              // defaultHttpClient
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);

              HttpResponse httpResponse = httpClient.execute(httpPost);
              HttpEntity httpEntity = httpResponse.getEntity();
              is = httpEntity.getContent();

              BufferedReader reader = new BufferedReader(new InputStreamReader(
                              is, "iso-8859-1"), 8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
              }
              is.close();
              json = sb.toString();
      } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
      } catch (ClientProtocolException e) {
              e.printStackTrace();
      } catch (IOException e) {
              e.printStackTrace();
      }

      try {
              jObj = new JSONObject(json);
       } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
       }

             // return JSON String
           return jObj;

          }

             public void parseJson(JSONObject json) {
            try {

              // parsing json object
              if (json.getString("status").equalsIgnoreCase("ok")) {
                      JSONArray posts = json.getJSONArray("posts");


                      feedList = new ArrayList<FeedItem>();

                      for (int i = 0; i < posts.length(); i++) {
                              JSONObject post = (JSONObject) posts.getJSONObject(i);
                              FeedItem item = new FeedItem();
                              item.setTitle(post.getString("title"));
                              item.setDate(post.getString("description"));
                              item.setId(post.getString("id"));
                              item.setUrl(post.getString("url"));
                              item.setContent(post.getString("description"));
                              item.setInfoz(post.getString("description"));
                              JSONArray attachments = post.getJSONArray("attachments");

                              if (null != attachments && attachments.length() > 0) {
                                      JSONObject attachment = attachments.getJSONObject(0);
                                      if (attachment != null)
                                              item.setAttachmentUrl(attachment.getString("url"));
                              }

                              feedList.add(item); 

                      }
              }
      } catch (JSONException e) {
              e.printStackTrace();
      }
       }
公共类Fragment1扩展了Fragment{
私有ArrayList feedList=null;
private ProgressBar ProgressBar=null;
私有ListView feedListView=null;
@凌驾
创建视图上的公共视图(布局充气机、视图组容器、捆绑包保存状态){
视图根视图=充气机。充气(R.layout.activity\u post\u list,container,false);
progressbar=(progressbar)rootView.findviewbyd(R.id.progressbar);
字符串url=“”;
新建下载文件任务().execute(url);
返回rootView;
} 
公共void updateList(){
feedListView=(ListView)getActivity().findViewById(R.id.custom_列表);
feedListView.setVisibility(View.VISIBLE);
if(progressbar.isShown()){
progressbar.setVisibility(View.GONE);
}
setAdapter(新的CustomListAdapter(getActivity(),feedList));
setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共视图单击(适配器视图a、视图v、内部位置、长id){
对象o=feedListView.getItemAtPosition(位置);
FeedItem newsData=(FeedItem)o;
Intent Intent=new Intent(getActivity(),FeedDetailsActivity.class);
intent.putExtra(“提要”,新闻数据);
星触觉(意向);
}
});
}
公共类DownloadFilesTask扩展了AsyncTask{
@凌驾
受保护的void onProgressUpdate(整型…值){
}
@凌驾
受保护的void onPostExecute(void结果){
如果(空!=提要列表){
updateList();
}
}
@凌驾
受保护的Void doInBackground(字符串…参数){
字符串url=params[0];
//从URL获取JSON字符串
JSONObject json=getJSONFromUrl(url);
//解析json数据
parseJson(json);
返回null;
}
}
公共JSONObject getJSONFromUrl(字符串url){
InputStream=null;
JSONObject jObj=null;
字符串json=null;
//发出HTTP请求
试一试{
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
公共void parseJson(JSONObject json){
试一试{
//解析json对象
if(json.getString(“status”).equalsIgnoreCase(“ok”)){
JSONArray posts=json.getJSONArray(“posts”);
feedList=新的ArrayList();
对于(int i=0;i0){
JSONObject附件=附件。getJSONObject(0);
如果(附件!=null)
item.setAttachmentUrl(attachment.getString(“url”));
}
添加(项);
}
}
}捕获(JSONException e){
e、 printStackTrace();
}
}

这很简单:您可以重写该方法并保存任何想要超越它的状态。然后,在
onCreateView()
中,您可以从对象
savedInstanceState
读取状态(如果有的话,它可能会在第一次启动时为null)。

我在saveInstanceState上添加了这个@override public void(Bundle outState){super.onSaveInstanceState(outState);outState.putParcelableArrayList(“提要列表”)(ArrayList@SandraMladenovic要使用putParcelable()方法,您需要使FeedItem实现Parcelable-请参阅,但我已经实现了公共类FeedItem可序列化,无法实现和Parcelable,什么