0

我正在執行tablayout使用view pager和在我的情況下我有兩個tab。在我的第一個tab我有添加數據存儲在share preference。而當我移動到第二個標籤時,則應從share preference中檢索數據並在listview中顯示。當我從我的第一個tab添加數據,然後數據添加成功,但不顯示在我的第二個tab意味着我必須關閉我的應用程序,並再次重新啓動應用程序,以便我可以看到保存從我的第一個tab保存的細節。 以下是我的活動代碼。Tablayout刷卡不刷新android

public class FragmentExample extends AppCompatActivity { 

    private ViewPagerAdapter viewPagerAdapter; 

    @BindView(R.id.tabCountryState) 
    TabLayout tabCountryState; 

    @BindView(R.id.viewPager) 
    ViewPager viewPager; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_fragment_example); 
     ButterKnife.bind(this); 


     setViewPager(); 
     setTabIcon(); 
     viewPager.setOffscreenPageLimit(2); 


     tabCountryState.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 
       Log.e("Current tab is ", "===> " + tab.getPosition()); 
      } 

      @Override 
      public void onTabUnselected(TabLayout.Tab tab) { 

      } 

      @Override 
      public void onTabReselected(TabLayout.Tab tab) { 
      } 
     }); 
    } 

    private void setViewPager() { 
     // set Adaapter. 
     viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentExample.this); 
     viewPager.setAdapter(viewPagerAdapter); 
     tabCountryState.setupWithViewPager(viewPager); 
    } 

    // set custom icon to tab in Tablayout. 
    private void setTabIcon() { 
     // First Tab 
     View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_first, null); 
     TextView tvFirsIcon = ButterKnife.findById(firstTab, R.id.tvFirsIcon); 
     tvFirsIcon.setText("First Tab"); 
     tabCountryState.getTabAt(0).setCustomView(firstTab); 

     // First Tab 
     View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_second, null); 
     TextView tvSecondIcon = ButterKnife.findById(secondTab, R.id.tvSecondIcon); 
     tvSecondIcon.setText("Second Tab"); 
     tabCountryState.getTabAt(1).setCustomView(secondTab); 
    } 

    public class ViewPagerAdapter extends FragmentStatePagerAdapter { 

     private Context context; 
     private FirstFragment firstFragment; 
     private SecondFragment secondFragment; 

     public ViewPagerAdapter(FragmentManager fm, Context mainActivity) { 
      super(fm); 
      context = mainActivity; 
      new FirstFragment(); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      switch (position) { 
       case 0: 
        firstFragment = new FirstFragment(); 
        return firstFragment; 

       case 1: 
        secondFragment = new SecondFragment(); 
        return secondFragment; 

       default: 
        return null; 
      } 
     } 

     @Override 
     public int getCount() { 
      return 2; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      return " " + position; 
     } 
    } 
} 

這是我的FirstFragment,其中我已將數據添加到共享首選項中。

public class FirstFragment extends Fragment { 

    private View v; 
    @BindView(R.id.btnSubmit) 
    Button btnSubmit; 

    @BindView(R.id.edtCityName) 
    EditText edtCityName; 

    @BindView(R.id.spStateName) 
    Spinner spStateName; 

    private Unbinder unbinder; 
    private ArrayList<String> alStateName; 
    private ArrayList<AllStateCityModel> alAllStateCity; 
    private SpinnerStateAdapter spinnerAdapter; 
    private int spinnerPosition; 
    private String strCityName, strSpinnerValue; 


    @OnClick(R.id.btnSubmit) 
    public void submit(View view) { 

     if (spinnerPosition !=0) { 

      strCityName = edtCityName.getText().toString().trim(); 
      alAllStateCity = SessinoManager.getCityList(getActivity()); 

      if (strCityName.length() > 0) { 
       alAllStateCity.get(spinnerPosition).getAlCityName().add(new CityStateModel(strCityName)); 
      } else { 
      } 

      // Save new data to Session. 
      SessinoManager.saveCityList(getActivity(), alAllStateCity); 

      SecondFragment.cityAdapter.notifyDataSetChanged(); 

      Toast.makeText(getActivity(), "Detail saved successfully ", Toast.LENGTH_SHORT).show(); 
      edtCityName.setText(""); 

     } else { 
      Toast.makeText(getActivity(), "Please select state", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     Bundle args = getArguments(); 
     v = inflater.inflate(R.layout.fragment_first, container, false); 
     unbinder = ButterKnife.bind(this, v); 

     // arraylist checking if data is available into session. 
     if(SessinoManager.getCityList(getActivity()).size()>0){ 
      Log.e("First fragment "," if condition "); 
      alAllStateCity = SessinoManager.getCityList(getActivity()); 

      alStateName = new ArrayList<>(); 
      for(int i=0;i<alAllStateCity.size();i++){ 
       alStateName.add(alAllStateCity.get(i).getStrStateName()); 
      } 
      setStateSpinner(); 
     }else{ 
      loadArraylist(); 
      setStateSpinner(); 
     } 
     return v; 
    } 

    private void setStateSpinner() { 

     spStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
       spinnerPosition = i; 
       spinnerAdapter.notifyDataSetChanged(); 
       strSpinnerValue = alStateName.get(i).toString().trim(); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> adapterView) { 
      } 
     }); 

     spinnerAdapter = new SpinnerStateAdapter(getActivity(), alStateName); 
     spStateName.setAdapter(spinnerAdapter); 
    } 

    private void loadArraylist() { 

     alAllStateCity = new ArrayList<>(); 
     alStateName = new ArrayList<>(); 


     alStateName.add(0, "Select State"); 
     alStateName.add("Gujarat"); 
     alStateName.add("Maharashtra"); 
     alStateName.add("Madhya Pradesh"); 


     for (int i = 0; i < alStateName.size(); i++) { 
      alAllStateCity.add(new AllStateCityModel(alStateName.get(i), alAllStateCity.size(), new ArrayList<CityStateModel>())); 
     } 

     SessinoManager.saveCityList(getActivity(), alAllStateCity); 
    } 

    @Override public void onDestroyView() { 
     super.onDestroyView(); 
     unbinder.unbind(); 

     Log.e("First fragment "," on destroy"); 
    } 
} 

這是我SecondFragment中,我不得不去從Share preference保存的細節。

public class SecondFragment extends Fragment { 

    private View v; 
    private Unbinder unbinder; 

    @BindView(R.id.lvCityList) 
    ListView lvCityList; 

    @BindView(R.id.spinnerStateName) 
    Spinner spinnerStateName; 

    private ArrayList<AllStateCityModel> alAllStateCity; 
    private ArrayList<CityStateModel> alCityName; 
    private ArrayList<String> alStateName; 
    private int spinnerPosition; 
    private SpinnerStateAdapter spinnerAdapter; 
    private ArrayList<String> alCity; 
    public static CityAdapter cityAdapter; 
    private Context context; 


    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     Bundle args = getArguments(); 
     v = inflater.inflate(R.layout.fragment_two, container, false); 
     unbinder = ButterKnife.bind(this, v); 

     context = getActivity(); 

     loadArrayList(context); 

     Log.e("onCreateView", "onCreateView"); 

     return v; 
    } 
    private void loadArrayList(Context context) { 

     alCityName = new ArrayList<>(); 
     alStateName = new ArrayList<>(); 
     alAllStateCity = SessinoManager.getCityList(context); 

     for (int j = 0; j < alAllStateCity.size(); j++) { 
//   Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName()); 

      // get state name from session 
      alStateName.add(alAllStateCity.get(j).getStrStateName()); 

      setSpinner(context); 
     } 
    } 

    private void setSpinner(Context context) { 

     spinnerAdapter = new SpinnerStateAdapter(context, alStateName); 
     spinnerStateName.setAdapter(spinnerAdapter); 

     spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
       spinnerPosition = i; 
       spinnerAdapter.notifyDataSetChanged(); 

       setList(spinnerPosition); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> adapterView) { 

      } 
     }); 
    } 

    private void setList(int position) { 

     alCityName = alAllStateCity.get(position).getAlCityName(); 
     alCity = new ArrayList<>(); 

     for (int i = 0; i < alCityName.size(); i++) { 
//    Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity()); 
      alCity.add(alCityName.get(i).getStrCity()); 
     } 

     cityAdapter = new CityAdapter(context, alCity); 
     lvCityList.setAdapter(cityAdapter); 
     cityAdapter.notifyDataSetChanged(); 

    } 

} 

而且我將數據保存到Share preference其中如下。

public class SessinoManager { 

    private static final String CITY_PREFERENCE = "city_preference"; 

    // Save data to share preference. 
    public static void saveCityList(Context context, ArrayList<AllStateCityModel> alAllPlayList) { 
     try { 
      SharedPreferences settings; 
      SharedPreferences.Editor editor; 

      settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE); 
      editor = settings.edit(); 

      Gson gson = new Gson(); 
      String jsonUsers = gson.toJson(alAllPlayList); 
      editor.putString("all_play_list", jsonUsers); 
      editor.commit(); 

      // Check to save data into share preferent 
      for(int j=0;j<alAllPlayList.size();j++){ 
       Log.e("State name ","----------------------"+alAllPlayList.get(j).getStrStateName()); 
       ArrayList<CityStateModel> cityName = alAllPlayList.get(j).getAlCityName(); 
       for(int i=0;i<cityName.size();i++){ 
        Log.e("cityName "," in session ==> "+cityName.get(i).getStrCity()); 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public static ArrayList<AllStateCityModel> getCityList(Context context) 
    { 
     SharedPreferences settings; 
     List<AllStateCityModel> users = new ArrayList<>(); 

     settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE); 

     if (settings.contains("all_play_list")) 
     { 
      String jsonUsers = settings.getString("all_play_list", null); 
      Gson gson = new Gson(); 
      AllStateCityModel[] userItems = gson.fromJson(jsonUsers,AllStateCityModel[].class); 

      users = Arrays.asList(userItems); 
      users= new ArrayList<AllStateCityModel>(users); 
     } 
     return (ArrayList<AllStateCityModel>) users; 
    } 
} 

當我添加新的城市詳細到第一選項卡,然後數據是成功的,但是當我刷卡或移至下一則數據不顯示,我必須重新啓動整個應用程序從Share preference.獲取更新數據請幫助我解決這個問題。提前致謝。

回答

0

我已通過執行以下方法setUserVisibleHint解決了該問題。

public class SecondFragment extends Fragment { 

    private View v; 
    private Unbinder unbinder; 

    @BindView(R.id.lvCityList) 
    ListView lvCityList; 

    @BindView(R.id.spinnerStateName) 
    Spinner spinnerStateName; 

    private ArrayList<AllStateCityModel> alAllStateCity; 
    private ArrayList<CityStateModel> alCityName; 
    private ArrayList<String> alStateName; 
    private int spinnerPosition; 
    private SpinnerStateAdapter spinnerAdapter; 
    private ArrayList<String> alCity; 
    public static CityAdapter cityAdapter; 
    private Context context; 


    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     Bundle args = getArguments(); 
     v = inflater.inflate(R.layout.fragment_two, container, false); 
     unbinder = ButterKnife.bind(this, v); 

     context = getActivity(); 

     loadArrayList(context); 

//  Log.e("onCreateView", "onCreateView"); 

     return v; 
    } 

    private void loadArrayList(Context context) { 

     alCityName = new ArrayList<>(); 
     alStateName = new ArrayList<>(); 
     alAllStateCity = SessinoManager.getCityList(context); 

     for (int j = 0; j < alAllStateCity.size(); j++) { 
//   Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName()); 

      // get state name from session 
      alStateName.add(alAllStateCity.get(j).getStrStateName()); 

      setSpinner(context); 
     } 
    } 

    @Override 
    public void setUserVisibleHint(boolean isVisibleToUser) { 
     super.setUserVisibleHint(isVisibleToUser); 
     Log.e("setUserVisibleHint","setUserVisibleHint "+isVisibleToUser); 

     if(isVisibleToUser==true){ 
      loadArrayList(context); 
     } 

    } 

    @Override 
    public boolean getUserVisibleHint() { 
     Log.e("getUserVisibleHint","getUserVisibleHint "+super.getUserVisibleHint()); 
     return super.getUserVisibleHint(); 

    } 

    private void setSpinner(Context context) { 

     spinnerAdapter = new SpinnerStateAdapter(context, alStateName); 
     spinnerStateName.setAdapter(spinnerAdapter); 

     spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
       spinnerPosition = i; 
       spinnerAdapter.notifyDataSetChanged(); 

       setList(spinnerPosition); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> adapterView) { 

      } 
     }); 
    } 

    private void setList(int position) { 

     alCityName = alAllStateCity.get(position).getAlCityName(); 
     alCity = new ArrayList<>(); 

     for (int i = 0; i < alCityName.size(); i++) { 
//    Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity()); 
      alCity.add(alCityName.get(i).getStrCity()); 
     } 

     cityAdapter = new CityAdapter(context, alCity); 
     lvCityList.setAdapter(cityAdapter); 
     cityAdapter.notifyDataSetChanged(); 

    } 
}