2016-09-19 5 views
0

하나의 액티비티가 있으며, listView와 함께 조각화하고 각 listView 항목에 대한 세부 정보로 조각화합니다. API에서 조각 데이터를 가져 오는 중입니다. listView로 돌아갈 때 복원 할 수 있도록로드 된 날짜 및 listView 위치를 올바르게 저장해야합니까? 이 솔루션 Once for all, how to correctly save instance state of Fragments in back stack?을 구현하려고했지만 listView를 올바르게 복원 할 수 없습니다.로드 된 listView 상태를 조각에 저장하는 방법은 무엇입니까?

내 MainActivity

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     //Set the fragment initially 
     listFragment = new ListFragment(); 
     fragmentTransaction = 
       getSupportFragmentManager().beginTransaction(); 
     fragmentTransaction.replace(R.id.fragment_container, listFragment); 
     fragmentTransaction.commit(); 

     if (savedInstanceState != null) { 
      //Restore the fragment's instance 
      listFragment = (ListFragment)getSupportFragmentManager().getFragment(savedInstanceState, "listContent"); 
     } 
... 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
     //Save the fragment's instance 
     getSupportFragmentManager().putFragment(outState, "listContent", listFragment); 
    } 

및 ListFragment

public class ListFragment extends Fragment { 

    public static final String REQUEST_TAG = "ProjectListFragment"; 

    private int page; 
    private View view; 
    private RelativeLayout loading ; 
    private PagingListView listView; 
    private PagingProjectListAdapter adapter; 
    private ArrayList<String> projects = new ArrayList<>(); 
    private ArrayList<String> loadedProjects = new ArrayList<>(); 

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

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

     listView = (PagingListView) view.findViewById(R.id.projectsListView); 
     loading = (RelativeLayout) view.findViewById(R.id.loading); 
     //page = 1; 
     adapter = new PagingProjectListAdapter(getContext(), ListFragment.this); 
     listView.setAdapter(adapter); 
     listView.setHasMoreItems(true); 

     // Inflate the layout for this fragment 
     return view; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     if (savedInstanceState != null) { 
      // FIXME not used 
      listView.onFinishLoading(true, projects); 
      //Restore the fragment's state here 
     } else { 
      projects.clear(); 
      page = 1; 

      listView.setPagingableListener(new PagingListView.Pagingable() { 
       @Override 
       public void onLoadMoreItems() { 
        new CustomVolleyAsyncTask().execute(); 
       } 
      }); 
     } 
    } 

    @Override 
    public void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
     outState.putInt("currentPosition", 0); 
     //Save the fragment's state here 
    } 

    public void itemClickMethod(View detailsView) { 
     LinearLayout linearLayout = (LinearLayout) detailsView; 
     String bid = linearLayout.getContentDescription().toString(); 

     Bundle bundle = new Bundle(); 
     String k = "ProjectID"; 
     bundle.putString(k, bid); 

     DetailsFragment detailsFragment = new DetailsFragment(); 
     detailsFragment.setArguments(bundle); 

     final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     ft.replace(R.id.fragment_container, detailsFragment, "DetailsFragmentTag"); 
     ft.addToBackStack(null); 
     ft.commit(); 
    } 

    private class CustomVolleyAsyncTask extends SafeAsyncTask<List<String>> implements Response.Listener, 
      Response.ErrorListener { 

     public List<String> status = null; 
     private RequestQueue mQueue; 

     @Override 
     public List<String> call() throws Exception { 
      mQueue = CustomVolleyRequestQueue.getInstance(view.getContext()) 
        .getRequestQueue(); 
      String url = "http://www.myapi.com/api/v1/data/" + Integer.toString(page); 
      final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method 
        .GET, url, 
        new JSONObject(), this, this); 
      jsonRequest.setTag(REQUEST_TAG); 
      mQueue.add(jsonRequest); 
      // TODO rm redundant result 
      return status; 
     } 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      // FIXME check no response case crash 
      //mTextView.setText(error.getMessage()); 
     } 

     @Override 
     public void onResponse(Object response) { 
      try { 
       JSONArray projectsJSON = new JSONArray(((JSONObject) response).getString("projects")); 
       loadedProjects.clear(); 
       for (int i=0; i < projectsJSON.length(); i++) { 
        loadedProjects.add(projectsJSON.getJSONObject(i).toString()); 
       } 
       page++; 

       listView.onFinishLoading(true, loadedProjects); 
       if (loading.getVisibility() == View.VISIBLE && !listView.isLoading()){ 
        listView.setVisibility(View.VISIBLE); 
        loading.setVisibility(View.GONE); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      }}} 
} 

현재, 내 savedInstanceState 항상 null의 경우, 내가 무엇을 놓치고?

+0

onSaveInstanceState()가 호출 되었습니까? –

답변

0

내가 생각하기에, 당신의 단편은 구성이 변경되었을 때 두 번 만들어 졌다고 생각합니다. Here Staffan이 설명합니다. 왜 이런 일이 일어 났습니까? 비슷한 방법으로 (onCreate 작업에서) 비슷한 문제를 해결합니다.

 FragmentManager fragmentManager = getSupportFragmentManager(); 
     Fragment fragment = fragmentManager.findFragmentByTag(TAG); 
     if(fragment==null) 
      fragmentManager.beginTransaction() 
        .add(R.id.container, NewsFragment.newInstance(),TAG) 
        .commit(); 
관련 문제