grid view does not refresh - android

I've got a problem with gridview. I'm using custom adapter and custom view for every item (months) in the adapter.
http://cs622428.vk.me/v622428086/3f452/K30qwCnc-iQ.jpg
When I go to another fragment and then press back, the gridview disappears.
http://cs622428.vk.me/v622428086/3f45c/2sbbchFTYgM.jpg
=================================================================
Sorry for tangled code. There was only 2 fragments when I faced the problem but then I decided to try to replace a whole fragment every time I need to update something. But still it doesn't work even when I call onResume in the first activity and replace everything...
So how can I refresh it ? It does not work:
#Override
public void onResume() {
super.onResume();
gridViewAdapter = new GridViewAdapter(getActivity(), currentYear.getMonths());
gridView.setAdapter(gridViewAdapter);
gridViewAdapter.notifyDataSetChanged();
gridView.setOnItemClickListener(this);
}
Adapter:
public class GridViewAdapter extends ArrayAdapter<Month> {
private Context context;
private ArrayList<Month> months;
public GridViewAdapter(Context context, ArrayList<Month> months) {
super(context, 0, months);
this.context = context;
this.months = months;
}
public ArrayList<Month> getData() {
return months;
}
#Override
public int getCount() {
return months.size();
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = new DrawSingleMonthView(context, months.get(i));
return view;
//return new DrawSingleMonthView(context, months.get(i));
}
Flagment - controller. There I call single month (double click) or all months.
public class CalendarFragment extends Fragment implements OnClickCalendarListener {
private FragmentTransaction fTrans;
private Year year;
private Year secondYear;
private Year thirdYear;
private Year currentYear;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Calendar calendar = GregorianCalendar.getInstance();
year = new Year(calendar.get(Calendar.YEAR));
secondYear = new Year(calendar.get(Calendar.YEAR) + 1);
thirdYear = new Year(calendar.get(Calendar.YEAR) + 2);
currentYear = year;
View v = inflater.inflate(R.layout.fragment_calendar_container, container, false);
return v;
}
#Override
public void onResume() {
super.onResume();
fTrans = getFragmentManager().beginTransaction();
AllMonthsFragment monthsFragment = new AllMonthsFragment(year, this);
fTrans.replace(R.id.fragment_calendar_container, monthsFragment);
fTrans.commit();
MonthFragment.addListener(this);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDoubleCalendarClick(int position) {
fTrans = getFragmentManager().beginTransaction();
SingleMonthFragment calendar = new SingleMonthFragment(currentYear.getMonths().get(position));
fTrans.replace(R.id.fragment_calendar_container, calendar);
fTrans.addToBackStack(null);
fTrans.commit();
}
This is the fragment where i replace all months on FrameLayout.
public class AllMonthsFragment extends Fragment implements View.OnClickListener{
private TextView yearTW;
private View v;
private FragmentTransaction fTrans;
private FrameLayout frameLayout;
private Year year;
private boolean flag;
CalendarFragment calendarFragment;
public AllMonthsFragment(Year year) {
this.year = year;
flag = false;
}
public AllMonthsFragment(Year year, CalendarFragment calendarFragment) {
this.year = year;
this.calendarFragment = calendarFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.calendar_all_month, container, false);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
yearTW = (TextView) v.findViewById(R.id.yearTW);
yearTW.setText("" + year.getNumberOfYear());
yearTW.setOnClickListener(this);
frameLayout = (FrameLayout) v.findViewById(R.id.container_months);
}
private void openCalendarMonthFragment () {
fTrans = getFragmentManager().beginTransaction();
MonthFragment monthFragment = new MonthFragment(year.getMonths());
fTrans.replace(R.id.container_months, monthFragment);
fTrans.commit();
}
#Override
public void onPause() {
super.onPause();
flag = true;
}
#Override
public void onResume() {
super.onResume();
if(flag) {
calendarFragment.onResume();
}
openCalendarMonthFragment();
}
#Override
public void onClick(View view) {
}
A fragment with gridlayout.
public class MonthFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
private FragmentTransaction fTrans;
private View v;
private GridView gridView;
private GridViewAdapter gridViewAdapter;
private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
private long lastClickTime = 0;
private ArrayList<Month> months;
private static List<OnClickCalendarListener> listeners;
MonthFragment (ArrayList<Month> months) {
this.months = months;
}
static {
listeners = new ArrayList<>();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_calendar_all_month, container, false);
gridView = (GridView) v.findViewById(R.id.gridView);
adjustGridView();
gridViewAdapter = new GridViewAdapter(getActivity(), months);
gridView.setAdapter(gridViewAdapter);
gridView.setOnItemClickListener(this);
gridView.setOnItemLongClickListener(this);
return v;
}
public static void addListener(OnClickCalendarListener onClickCalendarListener) {
listeners.add(onClickCalendarListener);
}
private static void notifyDoubleClick(int i) {
for (OnClickCalendarListener onClickCalendarListener : listeners)
onClickCalendarListener.onDoubleCalendarClick(i);
}
private void adjustGridView() {
gridView.setVerticalScrollBarEnabled(false);
}
private void onSingleClick(View v, int i) {
if (months.get(i).isSelected())
months.get(i).setSelected(false);
else months.get(i).setSelected(true);
v.invalidate();
}
private void onDoubleClick(int i) {
notifyDoubleClick(i);
}
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
onDoubleClick(i);
return false;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
onDoubleClick(i);
} else {
onSingleClick(v, i);
}
lastClickTime = clickTime;
view.invalidate();

User runOnUi Thread..!!! in setOnItemClickListner..!!
runOnUiThread(new Runnable() {
#Override
public void run() {
gridViewAdapter.notifyDataSetChanged();
}
});
Hope this help.!

Related

ViewPager and ImageGallery

The problem is this:
When you first choose a picture - everything is fine. If you swipe, and press the "back" button, after you open another image then will open last image which will opened.
The correct position is passed through the Bundle. I don’t understand where to look for the error.
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen, container, false);
ImageView imageView = view.findViewById(R.id.image_fScreen);
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
.into(imageView);
container.addView(view);
return view;
}
#Override
public int getCount() {
return hits.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
DialogFragment:
public class FullScreenDialogFragment extends DialogFragment {
private ArrayList<Hit> hits;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private TextView author;
private TextView count;
private int selectedPosition;
private Button buttonShare;
private static FullScreenDialogFragment fullScreenDialogFragment;
private int rlyPosition;
public static FullScreenDialogFragment getInstance() {
if (fullScreenDialogFragment == null) {
fullScreenDialogFragment = new FullScreenDialogFragment();
}
return fullScreenDialogFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_viewpager, container, false);
viewPager = view.findViewById(R.id.viewpager);
author = view.findViewById(R.id.author);
buttonShare = view.findViewById(R.id.btnShare);
count = view.findViewById(R.id.count);
hits = (ArrayList<Hit>) getArguments().getSerializable("hits");
selectedPosition = getArguments().getInt("position");
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(onViewPageChangeListener);
setItem(selectedPosition);
return view;
}
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
private void setItemInfo(int pos) {
count.setText((pos + 1) + " of " + hits.size());
Hit hit = hits.get(pos);
author.setText(hit.getUser());
}
ViewPager.OnPageChangeListener onViewPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
setItemInfo(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
I Guess the Problem is here
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
You might be passing the selectedPosition instead of currentPosition
Please check.
My problem was in creating DialogFramgent object.
I did it him in Singlton pattern and called it with old data.
Now in OnClick i'm created new object DialogFramget and him get new values.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fullScreenDialog = new FullScreenDialogFragment();
fullScreenDialog.setArguments(bundle);
fullScreenDialog.show(fragmentTransaction, "");

Android fragment lifecycle added more items into List on pressing back button

As i'm using FragNav library i have some items into List and when i switching on other fragment and after pressing on BackButton i have some other items into this List,
for example generally i have 1 item into List with RecyclerView after switching on other fragment and pressing back button on phone i have 2 items into RecyclerView and using onSaveInstanceState,
onActivityCreated couldn't resolve my problem
my Fragment:
public class HomeFragment extends BaseFragment implements IAnimationListener, View.OnClickListener, InstagramFeedsAdapter.OnClickListener {
...
// constructor
public static HomeFragment createInstance(int instance) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(BaseFragment.ARGS_INSTANCE, instance);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.instagram_post_container, container, false);
activity = getActivity();
context = getActivity().getBaseContext();
mediaUrls = new ArrayList<>();
feedsSchema = new FeedsSchema();
feedsSchema.setId(1);
mediaUrls.add("http://gizasystems.com/wp-content/uploads/2014/08/natural-world-hero3.jpg");
feedsSchema.setFeed_media_url(mediaUrls);
feedsSchema.setFollowers_count(10);
feedsSchema.setFollowings_count(20);
feedsSchema.setPage_name("my test");
feedsSchema.setType(FeedsSchema.feed_types.IMAGE);
items.add(feedsSchema);
instagram_feeds = mView.findViewById(R.id.instagram_feeds);
layoutManager = new LinearLayoutManager(context);
instagram_feeds.setLayoutManager(layoutManager);
instagram_feeds.setNestedScrollingEnabled(false);
instagramFeedsAdapter = new InstagramFeedsAdapter(activity, context, this, items);
return mView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
}
#Override
public void onAnimationEnd() {
}
#Override
public void onClick(View view) {
int clickedItem = view.getId();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onItemClick(View view, String transitionName, int position) {
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("someVarA", new ArrayList<>(items));
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
items = savedInstanceState.getParcelableArrayList("someVarA");
}
}
and my Adapter:
public class InstagramFeedsAdapter extends RecyclerView.Adapter<InstagramFeedsAdapter.InstagramFeedsViewHolder>
implements PreviewView.OnPreviewChangeListener {
private OnClickListener listener;
private List<FeedsSchema> feedsItems;
private Context context;
private boolean hoveredOnPopup = false;
private ExoPlayerManager exoPlayerManager;
private Activity activity;
private enum feedType {
IMAGE,
IMAGESLIDER,
VIDEO
}
public InstagramFeedsAdapter(Activity activity, Context context, OnClickListener listener, List<FeedsSchema> items) {
this.listener = listener;
this.feedsItems = items;
this.context = context;
this.activity = activity;
}
#Override
public void onBindViewHolder(#NonNull final InstagramFeedsViewHolder holder, int position) {
int feedType = feedsItems.get(position).getType().ordinal();
implementingGeneralViewData(holder, position);
if (feedType == 0) {
if (feedsItems.get(position).getFeed_media_url().size() > 1) {
implementingImageSliderView(holder, position);
} else {
implementingImageView(holder, position);
}
} else {
implementingVideoPlayerView(holder, position);
}
}
private void implementingVideoPlayerView(InstagramFeedsViewHolder holder, int position) {
}
#SuppressLint("CheckResult")
private void implementingImageSliderView(final InstagramFeedsViewHolder holder, final int position) {
}
#SuppressLint("CheckResult")
private void implementingImageView(final InstagramFeedsViewHolder holder, final int position) {
}
#Override
public int getItemCount() {
return feedsItems.size();
}
public class InstagramFeedsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, PopupInflaterListener, PopupStateListener, PopupOnHoverListener {
...
public InstagramFeedsViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
ButterKnife.bind(this, itemView);
}
#Override
public void onClick(View view) {
}
public void bind(int position) {
...
}
}

Tablayout on swipe not refreshing in android

I am implementing tablayout using view pager and in my scenario I have two tab. In my first tab I have add data which store in share preference. and when I move to second tab then data should be retrieve from share preference and show in listview. When I add the data from my first tab then data is added successfully but not show in my second tab means I have to close my application and again restart the app so that I can see saved the detail which saved from my first tab.
Below is my Activity code.
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;
}
}
}
Here is my FirstFragment in which I have added the data into share preference.
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");
}
}
Here is my SecondFragment in which I have to get saved detail from 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();
}
}
And I am saving data into Share preference which is given below.
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;
}
}
When I add new city detail into first tab then data is data successfully but when I swipe or move to next then data is not displaying and I have to restart whole application to get updated data from Share preference. Kindly help me to resolve this issue. Thanks in advance.
I have resolved the problem by implementing below method 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();
}
}

Calendar Swipe View Android

I'm trying to create a calendar similar to Google Calendar on Day mode, where you swipe through the days and see the hours
I'm stuck on how to update the date as the user swipes
here's what I have:
ListView Adapter
public class ListViewItems extends ArrayAdapter{
private Activity context;
private ArrayList<String> horarios;
public ListViewItems(Activity c, ArrayList<String> h){
super(c, R.layout.listview_item, h);
this.context = c;
this.horarios = h;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup){
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(R.layout.listview_item, null, true);
TextView hor = (TextView)v.findViewById(R.id.horario);
hor.setText(horarios.get(position));
return v;
}
}
EventsFragment where I set the adapter for the Viewpage
public class EventsFragment extends Fragment {
private SharedPreferences.Editor editor;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_events, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
ViewPager vp = (ViewPager)view.findViewById(R.id.viewpager);
SwipeAdapter sp = new SwipeAdapter(getActivity().getSupportFragmentManager());
vp.setAdapter(sp);
vp.setCurrentItem(249);
}
The Swipe Adapter
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new CalendarFragment();
return fragment;
}
#Override
public int getCount() {
return 500;
}
}
And my CalendarFragment where I populate the listView with the hours of the day
public class CalendarFragment extends Fragment {
private Integer currentPosition;
public CalendarFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
TextView text = (TextView)view.findViewById(R.id.day);
Calendar currentDate = Calendar.getInstance();
String day = Integer.toString(currentDate.get(Calendar.DAY_OF_MONTH));
text.setText(day);
ArrayList<String> horariosFixos = new ArrayList<String>();
horariosFixos.add("01:00");
horariosFixos.add("02:00");
horariosFixos.add("03:00");
horariosFixos.add("04:00");
horariosFixos.add("05:00");
horariosFixos.add("06:00");
horariosFixos.add("07:00");
horariosFixos.add("08:00");
horariosFixos.add("09:00");
horariosFixos.add("10:00");
horariosFixos.add("11:00");
horariosFixos.add("12:00");
horariosFixos.add("13:00");
horariosFixos.add("14:00");
horariosFixos.add("15:00");
horariosFixos.add("16:00");
horariosFixos.add("17:00");
horariosFixos.add("18:00");
horariosFixos.add("19:00");
horariosFixos.add("20:00");
horariosFixos.add("21:00");
horariosFixos.add("22:00");
horariosFixos.add("23:00");
horariosFixos.add("00:00");
ListViewItems events = new ListViewItems(getActivity(),horariosFixos);
ListView events_list = (ListView)view.findViewById(R.id.events_list);
events_list.setAdapter(events);
}
It's working, but I just can't figure out a way to update the date.
I tried a few things like storing the position given on SwipeAdapter and add or subtract a day from getInstance() but it didn't seem to work
Any help would be appreciated.
Ok well I don't know if I can answer your question definitively, but I may be able to help shed some light or give you food for thought.
In my code, I set a View Pager Listener. If you can do that in your code I think it would give you the functionality you are looking for.
Below is an example from one of my apps:
public void setViewPagerListener()
{
view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
//Log.i(TAG, "position: " + position);
// on changing the page
// make respected tab selected
//actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
//Log.i(TAG, "positionOffset: " + positionOffset);
if (positionOffset >= .7)
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.1f));
}
else if (positionOffset < .7 && positionOffset >= .4)
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.3f));
}
else if (positionOffset < .5 & positionOffset >= .2)
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.5f));
}
else if (positionOffset < .2 && !(positionOffset == 0))
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.7f));
}
}
#Override
public void onPageScrollStateChanged(int scrollState)
{
/*scrollState == 0 when the pager is idle and has finished it's scroll.*/
scroll_state_global = scrollState;
if (scrollState == 0 && view_pager.getCurrentItem() == 1)
{
scroll_state_global = -1;
frame_input_scrim.setVisibility(View.INVISIBLE);
view_pager.setVisibility(View.INVISIBLE);
}
}
});
}

ViewPager + ListView animation lag

I have a CarsFragment which is inculde cars. One page is one trade (Ferrari, Mercedes) and on every page has a list with models of actual trade.
The main view:
public class CarsFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cars_fragment, container, false);
pager = (ViewPager) view.findViewById(R.id.carsPager);
adapter = new CarsPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
return view;
}
}
Adapter:
public class CarsPagerAdapter extends FragmentStatePagerAdapter {
private final FragmentManager fm;
private String[] cars = new String[]{"Ferrari","Mercedes"};
public MatchesPageAdapter(final FragmentManager fm) {
super(fm);
this.fm = fm;
}
#Override
public int getCount() {
return cars.length;
}
#Override
public Fragment getItem(final int position) {
return FragmentModelList.newInstance(cars[position]);
}
#Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
super.destroyItem(container, position, object);
}
}
List:
public class FragmentModelList extends Fragment {
public static FragmentModelList newInstance(String trade) {
FragmentModelList fragmentModelList = new FragmentModelList();
Bundle args = new Bundle();
args.putString("trade", trade);
fragmentModelList.setArguments(args);
return fragmentModelList;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_matches_list_view, container, false);
list = (ListView) view.findViewById(R.id.modelList);
return view;
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
modelListAdapter = new ModelListAdapter(getActivity());
list.setAdapter(modelListAdapter);
loadModels();
}
private void loadModels() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(final Void... params) {
try {
List<Model> result = Downloader.getModelsByName(getArguments().getString("trade"));
modelListAdapter.setData(result);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (!success) {
// Show error
} else {
// Update list
modelListAdapter.notifyDataSetChanged();
}
}
}.execute();
}
}
and the modelListAdapter set row where one row inculde 2 image and some textview.
And the problem:
when i swiping on the viewpager it isn't smooth :( a loged it and when created the next or previous page (depends on swipe direction) the animation will be bad, is lagging.
What is the solution?
(SGS4 android 4.2.2 - where is the project butter :(( )

Categories

Resources