【问题标题】:Android how to savestate arraylistAndroid如何保存状态数组列表
【发布时间】:2013-11-02 15:03:09
【问题描述】:

我正在制作一个 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();
      }
       }

【问题讨论】:

    标签: java android save fragment restore


    【解决方案1】:

    这很简单:您可以覆盖方法onSaveInstanceState(bundle outState) 并将您想要的任何状态保存到outState。然后,在onCreateView() 中,您可以从对象savedInstanceState 中读取状态(如果有的话 - 它可能并且在首次启动时将为空),

    【讨论】:

    • 我已经添加了这个@Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList("feedList", (ArrayList extends Parcelable>) feedList); } 和这个 oncreateview feedList=savedInstanceState.getParcelableArrayList("feedList");但我收到错误绑定不匹配:Bundle 类型的通用方法 getParcelableArrayList(String) 不适用于参数(String)。推断的类型 FeedItem 不是有界参数 的有效替代品
    • @SandraMladenovic 您需要让 FeedItem 实现 Parcelable 才能使用 putParcelable() 方法 - 请参阅 developer.android.com/reference/android/os/Parcelable.html
    • 但是我已经公开类 FeedItem 实现了 Serializable 并且我无法实现 Parcelable,现在怎么办?
    • 为什么不两者兼而有之? implements Serializable, Parcelable
    • 好吧,当我对这条线进行打包时,我遇到了另一个问题 intent.putExtra("feed", newsData); putExtra 显示错误:方法 putExtra(String, Parcelable) 对于 Intent 类型不明确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2012-05-02
    相关资源
    最近更新 更多