How can passing data from ViewPagerAdapter to a different activity - android

I add to my app ViewPager to display a set of images I get the image from database.It works fine but I need to work (Intent) to image.So where user click on image he should go to a new activity and see that picture in it.I searched for a solution and could not find the solution.
If anyone Knew the solution help me please.
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<SliderUtils> sliderImg;
private ImageLoader imageLoader;
public ViewPagerAdapter(List sliderImg,Context context) {
this.sliderImg = sliderImg;
this.context = context;
}
#Override
public int getCount() {
return sliderImg.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout, null);
SliderUtils utils = sliderImg.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(utils.getSliderImageUrl(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher_round, android.R.drawable.ic_dialog_alert));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == 0){
Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
} else if(position == 1){
Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
public class FoodFregmaent extends Fragment {
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
RequestQueue rq;
List<SliderUtils> sliderImg;
ViewPagerAdapter viewPagerAdapter;
String request_url = "http://===========sliedshow.php";
public FoodFregmaent() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food_fregmaent, container, false);
rq = CustomVolleyRequest.getInstance(getContext()).getRequestQueue();
sliderImg = new ArrayList<>();
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)view. findViewById(R.id.SliderDots);
sendRequest();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
SliderUtils sliderUtils = new SliderUtils();
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderUtils.setSliderImageUrl(jsonObject.getString("imageurl"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapter = new ViewPagerAdapter(sliderImg, getActivity());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_launcher_background));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
} else if(viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
public class SliderUtils {
String imageurl;
public String getSliderImageUrl() {
return imageurl;
}
public void setSliderImageUrl(String imageurl) {
this.imageurl = imageurl;
}
}
Still I search about solution to it

You can add an Intent with a String that contains the image URL into your view.setOnClickListener within the instantiateItem() of the ViewPager
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// ... Other code is omitted
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Activity2.class); // Change the name of the other activity
intent.putExtra("url", sliderImg.get(position).getSliderImageUrl()); // add the image URL to the other activity
}
});
And at the target activity, receive the url with
String url = getIntent().getStringExtra("url")

Related

How can I implement a rotative banner for my Android app?

On my login activity I would like to have a banner (3 actually) which would switch by certain time. Just like news on a website. With an arrow to pass to the next one, but mainly that passes automatically.
An example of what I want, these images on Tinder login screen switch when I swipe or just wait:
How do I do something like this on Android? Is there a way to do it natively? or at least is there a external resource for that?
Try this code,
public class TestActivity extends AppCompatActivity {
int images[] = {R.drawable.ic_earth, R.drawable.oval_btn,
R.drawable.ic_group_black_24dp, R.drawable.ic_earth};
ImagePagerAdapter myAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tests);
ViewPager viewPager = findViewById(R.id.viewPager);
myAdapter = new ImagePagerAdapter(TestActivity.this, images);
viewPager.setAdapter(myCustomPagerAdapter);
setupViewPager(viewPager);
}
int currentPage = 0;
Timer timer;
final long DELAY_MS = 500;
final long PERIOD_MS = 3000;
int NUM_PAGES = 4;
private void setupViewPager(final ViewPager viewPager) {
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer .schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
public class ImagePagerAdapter extends PagerAdapter {
Context context;
int images[];
LayoutInflater layoutInflater;
public ImagePagerAdapter(Context context, int images[]) {
this.context = context;
this.images = images;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = layoutInflater.inflate(R.layout.item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}

I need to set unique ID/Text to fragment [duplicate]

I created an Tab based application using viewpager and Tablayout. When i click a button new tabs are created with a child fragment.
What I need is to assign different tab id to my tabs and each should be different. I tried i take the position of tabs but unfortunately, it doesn't work. when i tried to toast the position using below code it works only initially when the first tab is created and doesn't work for other tabs created. I don't know why this happens. ALso if i delete the tabs the position is not getting correct.
So I need an alternative solution to assign a TAB id (number or name) to each new tabs created so that when each tab is created I need to call a request to server with that id and populate data based on the tab ID
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
My ViewPageradapter is:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
//viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
ImageView tabItemAvatar =
(ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Parent Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void addPage(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
CHILD FRAGMENT :
public class FragmentChild extends Fragment {
String childname;
TextView textViewChildName;
EditText editText;
private GridView mGridView;
private ListItem mListItem;
private ListView mListview;
private ProgressBar mProgressBar;
private ProductViewAdapter mGridAdapter;
private ListViewAdapter mListAdapter = null;
private ArrayList<GridItem> mGridData;
private ArrayList<ListItem> mListData = null;
ListView listView;
CheckInterNetConnection check ;
Boolean isInternetPresent = false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
//textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
//textViewChildName.setText(childname);
//editText = (EditText) view.findViewById(R.id.editText);
//editText.setText("");
}
private void setEvents() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("onActivityCreated","onActivityCreated");
mGridView = (GridView) getView().findViewById(R.id.gridView);
mGridData = new ArrayList<>();
mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mListview = (ListView) getView().findViewById(R.id.list);
mListData = new ArrayList<>();
mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
mListview.setAdapter(mListAdapter);
}
#Override
public void onStart() {
super.onStart();
Log.e("onSTart","onSTart");
check = new CheckInterNetConnection(getActivity());
isInternetPresent = check.isConnectingToInternet();
if (isInternetPresent) {
//fetchProducts();
}
}
public void fetchProducts(){
Log.e("URL","http://13.126.17.194/products.php");
RestClientHelper.getInstance().get("http://13.126.17.194/products.php?tabid="{TAB ID HERE}, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
parseResult(response);
mListData.clear();
mListAdapter.setGridData(mListData);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ListItem items;
GridItem item = (GridItem) parent.getItemAtPosition(position);
items = new ListItem();
items.setName(item.getTitle());
items.setType(item.getDescription());
mListData.add(items);
}
catch(Exception e){
}
finally {
mListAdapter.setGridData(mListData);
}
}
});
}
#Override
public void onError(String error) {
}
});
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("products");
GridItem item;
if(posts.length() <= 0){
RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
ly.setVisibility(View.VISIBLE);
}
else {
// RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
//ly.setVisibility(View.INVISIBLE);
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String title = post.optString("name");
String description = post.optString("description");
String image = post.optString("image");
String qty = post.optString("qty");
String quantityin = post.optString("quantityin");
String price = post.optString("price");
item = new GridItem();
item.setId(id);
item.setTitle(title);
item.setDescription(description);
item.setImage(image);
item.setQuantity(qty);
item.setQuantityIn(quantityin);
item.setUnitprice(price);
mGridData.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
finally {
mGridAdapter.setGridData(mGridData);
}
}
}
PARENT FRAGMENT:
public class FragmentParent extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private ImageView add;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void addPage(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
//setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
PLEASE HELP ME TO SOLVE THIS
Here is my solution for the question:
First, create an id file under res/values named ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="tab_id_one" type="id"/>
<item name="tab_id_two" type="id"/>
</resources>
Then, within the code where tabs are created, do the following:
for (int i = 0; i< tabLayout.getTabCount(); i++) {
TabLayout.Tab mTab = tabLayout.getTabAt(i);
if (mTab != null) {
switch (i){
case 0:
View tabViewOne = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabViewOne.setId(R.id.tab_id_one);
//ect..
break;
case 1:
View tabViewTwo = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabViewTwo.setId(R.id.tab_id_two);
//ect..
break;
case 2:
//etc..
}
}
}
Note: Views tabViewOne and tabViewTwo can be made global variables where it will give access to their ids anywhere within the class/activity/fragment.
In your viewPager Adapter extends FragmentPagerAdapter this and include these methods and it will give new ID to every Fragment and when you add manually data in array and call notifyDataSetChange(), also call this method notifyChangeInPosition(mItems.size() - 1);.
From this the added item get a new ID.
private long baseId = 0;
ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return mItems.size();
}
//this is called when notifyDataSetChanged() is called
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
*
* #param n number of items which have been changed
*/
void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
You can use the setTag() method of TabLayout.Tab to use any Object you want as an identifier. You could do this in your setupTabLayout() method, where you are setting your custom view for each Tab.
For example, to use a String:
tabLayout.getTabAt(i).setTag("tab_" + i);
You can then later check the tag of each tab in your parent fragment with tab.getTag();

Data is not fetching when swap the tab

I have implemented one app where I have 7 tabs and I used addOnScrollListener to fetch the data when user will scroll the list. My issue is when I move one fragment or tab to another fragment and then come back on the privious tab, the data is not coming on second time on that tab.
Below is my fragment class
public class EI_Pending_Fragment extends Fragment{
SessionManager session;
private List<SuperHero> listSuperHeroes;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public ProgressBar progressBar;
private RequestQueue requestQueue;
private int requestCount1 = 1;
private Boolean isStarted = false;
private Boolean isVisible = false;
public String email;
public EI_Pending_Fragment() {}
#Override
public void onStart() {
super.onStart();
isStarted = true;
if (isVisible && isStarted){
getData();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isStarted && isVisible) {
getData();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.activity_main_test, container, false);
session = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
return view;
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
listSuperHeroes = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getContext());
// getData();
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
if (isLastItemDisplaying(recyclerView)) {
if(requestCount1==1){
exit();
}
else {
getData();
}
}
}
});
}
private JsonArrayRequest getDataFromServer(int requestCount) {
Log.e("email",email);
final String DATA_URL = "http://192.168.2.110/xp/ei_pending_received.php?matri_id="+email+"&page=";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response",response.toString());
if(response.length()==0){
requestCount1 = 1;
}
else {
parseData(response);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
return jsonArrayRequest;
}
private void getData() {
requestQueue.add(getDataFromServer(requestCount1));
requestCount1++;
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Log.e("array",array.toString().trim());
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config_Test.TAG_IMAGE_URL));
superHero.setMglId(json.getString(Config_Test.TAG_MGLID));
superHero.setAge(json.getString(Config_Test.TAG_AGE));
superHero.setAgeHeight(json.getString(Config_Test.TAG_HEIGHT));
superHero.setCommunity(json.getString(Config_Test.TAG_COMMUNITY));
superHero.setCaste(json.getString(Config_Test.TAG_CASTE));
superHero.setOccupation(json.getString(Config_Test.TAG_OCCUPATION));
superHero.setIncome(json.getString(Config_Test.TAG_INCOME));
superHero.setStatus(json.getString(Config_Test.TAG_STATUS));
superHero.setRequested_On(json.getString(Config_Test.TAG_REQUESTED_ON));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
adapter.notifyDataSetChanged();
}
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
void exit(){
Toast.makeText(getContext(),"no more data avilable",Toast.LENGTH_SHORT).show();
}
}
Below is my Activity class where I add all the tab
private void setupViewPager(ViewPager viewPager) {
int numberOfPages=7;
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new NewMatches_Tab(), "New matches");
adapter.addFragment(new Broader_Match_Tab(), "Broader Matches");
adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
adapter.addFragment(new ShortlistTab(), "ShortListed");
adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
//viewPager.setOffscreenPageLimit(numberOfPages);
viewPager.setAdapter(adapter);
}
You can add an OnPageChangeListener in the activity and register it to your view pager and do all necessary "setting" within the OnPageChangeListener instance.
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Do your fragment refreshing here
mCurrentPage = position;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
#Override
public void setFragmentsForContents(List<Content> contents) { //bundle data for your different fragments
if(contents!=null){
NUM_PAGES = contents.size();
mContentPager.addOnPageChangeListener(viewPagerPageChangeListener);
mContentPager.setAdapter(mScreenSlidePagerAdapter);
mContentPager.setCurrentItem(mCurrentPage);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(mContents.get(position).getContent());
}
#Override
public int getCount() {
return NUM_PAGES;
}
#NonNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public float getPageWidth(int position) {
return 1.0f;
}
}

How to notify all the listview with multiple checkboxes inside multiple fragments?

I've a viewpager looping a multiple fragments and set in a viewpager. Each fragment has a listview with checkbox. On clicking any one item of a list it will notify all the fragments so that all checkbox remains unchecked and only clicked item will be checked.
CreateGroupStep1
public class CreateGroupStep1 extends BaseActivity implements IGroup {
private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView next_btn,back;
private int current_item_position;
private ViewPagerAdapter adapter;
private ArrayList<Interest> interestList;
ArrayList<String>al_sports;
ArrayList<String>al_list_collect;
private ArrayList<String>al_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group_step1);
storeDataOfArrayList();
al_list_collect=new ArrayList<String>();
initViews();
}
public void initViews() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
RelativeLayout back=(RelativeLayout) findViewById(R.id.back);
back=(RelativeLayout) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
next_btn=(ImageView) findViewById(R.id.next_btn);
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent ii=new Intent(CreateGroupStep1.this,CreateGroupStep2.class);
//startActivity(ii);
Toast.makeText(CreateGroupStep1.this, "", Toast.LENGTH_SHORT).show();
}
});
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(CreateGroupStep1.this.getSupportFragmentManager());
for (int i=0;i<al_title.size();i++)
{
adapter.addFragment(InterestFragmentForGroup.getInstance(al_sports),al_title.get(i));
viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(10);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
current_item_position = position;
// Toast.makeText(CreateGroupStep1.this, "scrolled", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClickedNextButton(final String message) {
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CreateGroupStep1.this,message, Toast.LENGTH_SHORT).show();
}
});
}
public static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void storeDataOfArrayList()
{
saveData();
al_sports=new ArrayList<>();
al_sports.add("Baseball");
al_sports.add("Basketball");
al_sports.add("Bowling");
al_sports.add("Cricket");
al_sports.add("Football");
al_sports.add("Golf");
al_sports.add("Handball");
al_sports.add("Hockey");
al_sports.add("Jogging");
al_sports.add("Racquetball");
al_sports.add("Running");
al_sports.add("Skiing");
al_sports.add("Snowboarding");
al_sports.add("Soccer");
al_sports.add("Swimming");
al_sports.add("Tennis");
}
private void saveData()
{
al_title=new ArrayList<String>();
al_title.add("Sports");
al_title.add("LifeStyle");
al_title.add("Adventure");
al_title.add("Recreation");
al_title.add("The Arts");
al_title.add("College");
al_title.add("Sos");
al_title.add("Industry");
al_title.add("LocalBiz");
al_title.add("Corporate");
}
}
InterestAdapterForGroup
public class InterestAdapterForGroup extends RecyclerView.Adapter<InterestAdapterForGroup.MyViewHolder> implements IGroup {
public int selectedPosition = -1;
IGroup inter;
private LayoutInflater inflater;
private ArrayList<Interest> stList;
private Context mContext;
private ArrayList<Interest> checked_item = new ArrayList<>();
public InterestAdapterForGroup(Context context, ArrayList<Interest> al_list) {
this.mContext = context;
this.stList = al_list;
inflater = LayoutInflater.from(context);
inter = (IGroup) mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_ethnic, parent, false);
InterestAdapterForGroup.MyViewHolder holder = new InterestAdapterForGroup.MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final int pos = position;
final Interest interest = stList.get(position);
holder.title.setText(interest.getName());
if (position == selectedPosition) {
holder.chkSelected.setChecked(true);
} else {
holder.chkSelected.setChecked(false);
}
holder.chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
interest.isSelected = isChecked;
if (isChecked) {
checked_item.clear();
checked_item.add(interest);
selectedPosition = position;
} else {
checked_item.remove(interest);
selectedPosition = -1;
}
notifyDataSetChanged();
}
}
});
clickedItems();
}
public void clickedItems() {
if (checked_item.size() > 0) {
if (Constants.GLOBAL_ARRAY.size() > 0) {
Constants.GLOBAL_ARRAY.clear();
for (int i = 0; i < checked_item.size(); i++) {
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
}
}
ArrayList<String> al_name = new ArrayList<String>();
ArrayList<String> al_nam = new ArrayList<String>();
for (int i = 0; i < checked_item.size(); i++) {
al_name.add(checked_item.get(i).getEmailId());
}
for (int i = 0; i < checked_item.size(); i++) {
al_nam.add(checked_item.get(i).getName());
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
inter.onClickedNextButton(al_nam.toString());
}
public ArrayList<Interest> getCheckedItemList() {
return stList;
}
#Override
public int getItemCount() {
return stList.size();
}
#Override
public void onClickedNextButton(String message) {
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CheckBox chkSelected;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_ethnic);
chkSelected = (CheckBox) itemView
.findViewById(R.id.chk);
}
#Override
public void onClick(View v) {
}
}
}
InterestFragmentForGroup
public class InterestFragmentForGroup extends BasePagerFragment implements IPager {
private ArrayList<String> interestList;
private ArrayList<Interest> interestListfunction;
public static Fragment getInstance(ArrayList<String> interestList){
Bundle bundle = new Bundle();
bundle.putSerializable("interestList",interestList);
InterestFragmentForGroup interestsFragment = new InterestFragmentForGroup();
interestsFragment.setArguments(bundle);
return interestsFragment;
}
public void getInterestList(){
interestList = (ArrayList<String>) getArguments().getSerializable("interestList");
}
private RecyclerView recyclerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sports_fragment, container, false);
initViews(rootView);
return rootView;
}
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.drawerList);
getInterestList();
setData();
}
public void setData() {
interestListfunction = new ArrayList<>();
for (int i = 0; i < interestList.size(); i++) {
Interest st = new Interest(interestList.get(i), interestList.get(i), false);
interestListfunction.add(st);
}
adapter2 = new InterestAdapterForGroup(getActivity(), interestListfunction);
recyclerView.addItemDecoration(new DividerDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter2);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
}
}

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();
}
}

Categories

Resources