1

我有fragmentRecyclerView裏面。所有工作都很好,但是當我按回家時,在其他應用中導航,然後返回到我的應用中,視圖得到重新創建,我的recyclerview中不顯示ArrayList(即使在更新列表後也不起作用)。notifyDataSetChanged停止工作後onDestroy在片段

這裏一些代碼:

-activity

public class MainActivity extends AppCompatActivity { 

    FragmentTransaction ft; 
    BottomNavigationView bottomNavigationView; 
    int current; 
    private FirebaseAnalytics mFirebaseAnalytics; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     if(savedInstanceState==null) { 
      setupFragment(); 
     } 

//  mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); 


     bottomNavigationView = (BottomNavigationView) 
      findViewById(R.id.bottom_navigation); 

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

    bottomNavigationView.setOnNavigationItemSelectedListener(
      new BottomNavigationView.OnNavigationItemSelectedListener() { 
       @Override 
       public boolean onNavigationItemSelected(@NonNull MenuItem item) { 
        int id = item.getItemId(); 
        switch (id) { 
         case R.id.action_golden_hour: 
          changeFragment(new GoldenFragment(), "GOLDEN"); 
          current=0; 
          break; 
         case R.id.action_hyperfocal: 
          changeFragment(new HyperFragment(), "HYPER"); 
          current=1; 
          break; 
         case R.id.action_ir: 
          changeFragment(new IrFragment(), "IR"); 
          current=2; 
          break; 
         case R.id.action_nd: 
          changeFragment(new NdFragment(), "ND"); 
          current=3; 
          break; 
        } 
        return true; 
       } 
      }); 
} 

@SuppressLint("CommitTransaction") 
private void setupFragment(){ 
    ft = getSupportFragmentManager().beginTransaction(); 
    ft.add(R.id.main_fragment, new GoldenFragment()).commit(); 
    current=0; 
} 

@SuppressLint("CommitTransaction") 
private void changeFragment(Fragment fragment, String tag){ 
    ft = getSupportFragmentManager().beginTransaction(); 
    ft.replace(R.id.main_fragment, fragment, tag).commit(); 
} 

-Fragment

public class GoldenFragment extends Fragment implements DatePickerDialog.OnDateSetListener{ 

SupportPlaceAutocompleteFragment autocompleteFragment; 
RecyclerView rv; 
CustomAdapter adapter; 
ProgressBar pb; 
ArrayList<Hours> hours; 
CardView cv; 
TextView emptyGoldenText; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    thisContext = getContext(); 
    setHasOptionsMenu(true); 
    ampm = !android.text.format.DateFormat.is24HourFormat(thisContext); 

    hours = new ArrayList<>(); 
    adapter = new CustomAdapter(thisContext, hours); 

    if(savedInstanceState!=null) { 
     Log.d(TAG,"inState not null"); 
     hours.clear(); 
     hours = savedInstanceState.getParcelableArrayList("HoursList"); 
    } 

    Log.d(TAG,"onCreate() called"); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    if(view == null) { 
     view = inflater.inflate(R.layout.fragment_golden, container, false); 
    } 
    Toolbar goldenToolbar = (Toolbar) view.findViewById(R.id.toolbar_golden); 
    ((AppCompatActivity) getActivity()).setSupportActionBar(goldenToolbar); 

    emptyGoldenText = (TextView) view.findViewById(R.id.empty_golden_text); 

    autocompleteFragment = (SupportPlaceAutocompleteFragment) getChildFragmentManager() 
      .findFragmentById(R.id.place_autocomplete_fragment); 

    if (autocompleteFragment == null) { 
     autocompleteFragment = (SupportPlaceAutocompleteFragment) SupportPlaceAutocompleteFragment 
       .instantiate(thisContext, "com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment"); 
    } 
    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { 
     @Override 
     public void onPlaceSelected(Place place) { 
      Log.i(TAG, "Place: " + place.getName()); 
      try { 
       new GeoCoding() 
         .execute("https://maps.googleapis.com/maps/api/geocode/json?address="+place.getName()+"&key="+geoKEY); 
      } catch (Exception e) { 
       Toast.makeText(thisContext,"Cannot contact Google's servers, please try later.", Toast.LENGTH_SHORT).show(); 
       e.printStackTrace(); 
      } 
     } 

     @Override 
     public void onError(Status status) { 
      Log.i(TAG, "An error occurred: " + status); 
     } 
    }); 
    getChildFragmentManager().beginTransaction() 
      .replace(R.id.place_autocomplete_fragment, autocompleteFragment).commit(); 

    //Initialize RecyclerView 
    rv = (RecyclerView)view.findViewById(R.id.list_golden); 
    rv.setLayoutManager(new LinearLayoutManager(thisContext)); 
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), 
      getActivity().getResources().getConfiguration().orientation); 
    rv.addItemDecoration(dividerItemDecoration); 
    rv.setAdapter(adapter); 

    cv = (CardView) view.findViewById(R.id.cv_golden); 
    pb = (ProgressBar) view.findViewById(R.id.progress_bar); 

    if(savedInstanceState==null) { 
     Log.d(TAG,"New empty data set"); 

     rv.setVisibility(View.GONE); 
     cv.setVisibility(View.GONE); 
     pb.setVisibility(View.INVISIBLE); 
    } 
    else{ 
     Log.d(TAG,"Old data set"); 

     adapter.notifyDataSetChanged(); 
     pb.setVisibility(View.INVISIBLE); 
     rv.setVisibility(View.VISIBLE); 
     cv.setVisibility(View.VISIBLE); 
     emptyGoldenText.setVisibility(View.INVISIBLE); 
    } 

    Log.d(TAG,"onCreateView() called"); 
    return view; 
} 

@Override 
public void onSaveInstanceState(Bundle outState){ 
    super.onSaveInstanceState(outState); 
    outState.putParcelableArrayList("HoursList",hours); 
    Log.d(TAG,"onSaveInstanceState called"); 
} 

解決 通過移動

adapter = new CustomAdapter(thisContext, hours);解決()至onCreateView()。

回答

0

在活動中,您必須將片段的實例保存在onSaveInstanceState()中,並在onCreate()中恢復。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    ... 
    if (savedInstanceState != null) {  
     fragment = getSupportFragmentManager().getFragment(savedInstanceState, "KEY"); 
     changeFragment(fragment, "MY TAG") 
    } else { 
     setupFragment(); 
    } 
    ... 
} 


@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 

    Fragment fragment = getSupportFragmentManager().findFragmentByTag("MY TAG"); 
    if (fragment != null) { 
     getSupportFragmentManager().putFragment(outState, "KEY", fragment); 
    } 
} 
+0

這不起作用,該片段得到恢復,但仍RecyclerView不起作用。我確信ArrayList不是空的,而是adapter.notifydatasetchanged()什麼也不做。 – nellorocca

0

試試這個代碼:在onSaveInstanceState放的ArrayList

 @Override 
public void onSaveInstanceState(Bundle outState){ 
    super.onSaveInstanceState(outState); 
    outState.putParcelableArrayList("HoursList",hours); 
    Log.d(TAG,"onSaveInstanceState called"); 
    } 

onActivityCreated您檢查以下條件:

@Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     if(savedInstanceState! = null) { 
       //probably orientation change 
       Log.d(TAG,"inState not null"); 
       hours.clear(); 
       hours = savedInstanceState.getParcelableArrayList("HoursList"); 
       //check if u get the value print log 
      } 
     else { 
      if (hours != null) { 
       //returning from backstack, data is fine, do nothing 
      } else { 
       //newly created, compute data 
       hours = computeData(); 
      } 
     } 
    } 
+0

嘗試過但這不起作用。我認爲我的代碼做了同樣的事情,但在onCreate。問題是當我調用adapter.notifydatasetchanged:recyclerview不會被填充。 – nellorocca

+0

如果getItemCount()返回0,那麼notifyDataSetChanged()將不會執行任何操作。確保在初始化適配器時傳遞有效的數據集。 – rafsanahmad007

+0

看到這個:http://stackoverflow.com/questions/27714127/recyclerview-adapter-notifydatasetchanged-not-working – rafsanahmad007