Tablayout在刷卡上没有在android中刷新

时间:2017-01-07 10:11:41

标签: android android-fragments android-viewpager sharedpreferences android-tablayout

我正在使用tablayout实施view pager,在我的方案中,我有两个tab。在我的第一个tab中,我添加了存储在share preference中的数据。当我移动到第二个标签时,应该从share preference检索数据并显示在listview中。当我从第一个tab添加数据时,数据已成功添加但未显示在我的第二个tab中表示我必须关闭我的应用程序并再次重新启动应用程序以便我可以看到已保存的详细信息从我的第一个tab保存。 以下是我的活动代码。

    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.获取更新的数据请帮助我解决此问题。提前谢谢。

1 个答案:

答案 0 :(得分: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();

    }
}