Passing Data betwen Two Fragments - android

i have a main activity and alot with fragments in it .. now i want to pass data between fragment to another fragment
Help me with this ...
try to use intent but its never did what i want and errors occures
this is my source fragment :
public class SubCategoryDetail extends Fragment {
View view;
SubCategory subCategory;
SwipeRefreshLayout swipeRefreshLayout;
RecyclerView includedView, relatedView, popularView;
TextView titlePricing, titleIncluded, pricing1, pricing2;
Spinner spinner;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.subcategory_detail, container, false);
bindViews();
((HomeActivity) getActivity()).visibility(false, false, false);
return view;
}
private void bindViews() {
((HomeActivity) getActivity()).toolbar.setVisibility(View.VISIBLE);
Bundle bundle = getArguments();
if (bundle != null) {
subCategory = (SubCategory) bundle.getSerializable("data");
}
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
spinner = (Spinner) view.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new ItemSelectedListener());
getDetails();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getDetails();
}
});
}
Glide.with(getActivity()).load(subCategory.getImage()).into(bannerTop);
title.setText(subCategory.getName());
ImageAdapter imageAdapter = new ImageAdapter(subCategory.getImages(), getActivity());
recyclerView.setAdapter(imageAdapter);
description.setText(subCategory.getDescription());
IncludedAdapter includedAdapter = new IncludedAdapter(subCategory.getInclude(), getActivity());
includedView.setAdapter(includedAdapter);
PopularAdapter popularAdapter = new PopularAdapter(subCategory.getPopular(), getActivity());
popularView.setAdapter(popularAdapter);
TypefaceHelper.typeface(title, MyApplication.getBold());
TypefaceHelper.typeface(description, MyApplication.getLight());
TypefaceHelper.typeface(allProvider, MyApplication.getRegular());
TypefaceHelper.typeface(titleIncluded, MyApplication.getRegular());
TypefaceHelper.typeface(titlePricing, MyApplication.getRegular());
TypefaceHelper.typeface(pricing1, MyApplication.getLight());
TypefaceHelper.typeface(pricing2, MyApplication.getLight());
}
private void disableViews(Boolean what) {
for (int i = 0; i < swipeRefreshLayout.getChildCount(); i++) {
View child = swipeRefreshLayout.getChildAt(i);
child.setEnabled(what);
}
}
public class PopularAdapter extends RecyclerView.Adapter<PopularAdapter.Holder> {
private List<Category> list;
private Context context;
public PopularAdapter(List<Category> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public PopularAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new PopularAdapter.Holder(LayoutInflater.from(parent.getContext()).inflate(R.layout.popular_item, parent, false));
}
#Override
public void onBindViewHolder(PopularAdapter.Holder holder, int position) {
final Category category = list.get(position);
Glide.with(context).load(category.getImage())
.apply(new RequestOptions()
.placeholder(R.drawable.home)
.error(R.drawable.home)
.centerCrop())
.into(holder.icon);
holder.name.setText(category.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable("data", category);
bundle.putString("from", "one");
bundle.putString("name", category.getName());
SubCategoryFragment fragment = new SubCategoryFragment();
fragment.setArguments(bundle);
((HomeActivity) context).changeFragment(fragment, "Sub Category");
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class Holder extends RecyclerView.ViewHolder {
ImageView icon;
TextView name;
public Holder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.category_item);
name = (TextView) itemView.findViewById(R.id.cat_name);
TypefaceHelper.typeface(name, MyApplication.getLight());
}
}
}
Mainly this is what i want to pass !!
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(pos == 0) {
String ex = parent.getItemAtPosition(pos).toString();
String ex2 = ex.substring(ex.lastIndexOf("+") + 1);
}
else if(pos == 1) {
String ex = parent.getItemAtPosition(pos).toString();
String ex2 = ex.substring(ex.lastIndexOf("+") + 1);
Toast.makeText(parent.getContext(), ex2, Toast.LENGTH_LONG).show();
}
else if(pos == 2) {
String ex = parent.getItemAtPosition(pos).toString();
String ex2 = ex.substring(ex.lastIndexOf("+") + 1);
Toast.makeText(parent.getContext(), ex2, Toast.LENGTH_LONG).show();
}
else if(pos == 3) {
String ex = parent.getItemAtPosition(pos).toString();
String ex2 = ex.substring(ex.lastIndexOf("+") + 1);
Toast.makeText(parent.getContext(), ex2, Toast.LENGTH_LONG).show();
}
else if(pos == 4) {
String ex = parent.getItemAtPosition(pos).toString();
String ex2 = ex.substring(ex.lastIndexOf("+") + 1);
Toast.makeText(parent.getContext(), ex2, Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
please tell me the way that i can pass this data to a textview in the second fragment

If you want to pass the data to a fragment say myFragment then see snippet below
Bundle bundle=new Bundle();
bundle.putString("message",msg); //here msg is value you want to pass
myFragment fragment=new myFragment();
fragment.setArguments(bundle);`
now to access this in myFragment class using code (generally declared in oncreate() of fragment class):
Bundle bundle=getArguments();
if(bundle!=null){
Textiew textView.setText(String.valueOf(bundle.getString("message")));
}

Related

How to get the data from the fragment in viewpager when dynamically added fragments are swiped in swipeable tabs?

I am working on an app that includes shopping feature and items are added to cart.
I have navigation drawer. In that, I have my first fragment called as "POSFragment" in which I have implemented a viewpager as data to be shown in the form of swipeable tabs. The data will be inflated dynamically. So, I have used PagerTabStrip and a viewpager. There is a common fragment called "MenuDetailFragment" in which data will be inflated dynamically through a webservice. the adapter for this fragment is "MenuPagerAdapter". Now, In this fragment the data will shown in listview. In Listview in each row items can be incremented or decremented using plus and minus Buttons in each row. Between these button there is textview where the quantity will be displayed correspondingly. I have used a Linkedhashmap on both buttons so, the items along with the quantity is saved in linkedhashmap and then in Sharedpreferences. It's working fine till now. The issue occurs when I swipe in the View pager and next fragment appears and When I click on increment button or decrement button on item there. In shared preferences, It starts saving the current fragment items and previous fragment data is not there anymore. I have already used the "yourcustomviewpager.setOffscreenPageLimit(3)" So, I can see the selected items with the quantities whe I swipe to and fro but the data i stored in sharedpreferences using Linkedhashmap is not there instead current fragment's data is saved. I want that the new data is added to previous data and data in all the fragments should persist. Is there a way to do so? I have been facing this issue for quite a long time.
Here are some screenshots and relevant code snippet.
public class PosFragment extends Fragment {
private ViewPager viewPager;
View rootview;
String code;
String name;
String desc;
String rate;
String key;
Button viewCartBtn;
static TextView displayPrice;
static TextView noOfItemsInCart;
RippleView rippleView;
//private sendPosition pos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Log.e("oncreateview", "called");
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.pos_fragment_layout, container, false);
initViews();
new AsyncTaskGetMenu().execute();
return rootview;
}
public void initViews() {
Log.e("init", "called");
viewPager = (ViewPager) rootview.findViewById(R.id.viewPager);
Button viewCartButton = (Button) rootview.findViewById(R.id.view_cart_btn);
viewPager.setOffscreenPageLimit(3);
viewCartBtn = (Button) rootview.findViewById(R.id.view_cart_btn);
AppMethods.setGlametrixBoldFont(getActivity(), viewCartBtn);
displayPrice = (TextView) rootview.findViewById(R.id.textView_totalprice_cart);
noOfItemsInCart = (TextView) rootview.findViewById(R.id.cart_items_quantity);
viewCartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ViewCartActivity.class);
intent.putExtra(AppConstants.SUBTOTAL, Integer.parseInt(displayPrice.getText().toString()));
startActivity(intent);
}
});
LinearLayout itemsInCartLinearLayout = (LinearLayout) rootview.findViewById(R.id.ll_items_in_cart);
itemsInCartLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ViewCartActivity.class);
intent.putExtra(AppConstants.SUBTOTAL, Integer.parseInt(displayPrice.getText().toString()));
startActivity(intent);
}
});
}
This is "MenuDetailFragment" class
public class MenuDetailFragment extends Fragment {
View rootview;
private ListView listView;
private ArrayList<MenuHeadingDetailsModel> menuheadingDetailList;
private Communicate comm;
LinkedHashMap<String, ViewCartDetailsModel> viewCartDetailsModelMap = new LinkedHashMap<>();
ViewCartDetailsModel viewCartDetailsModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.menu_list, container, false);
InitializeViews();
return rootview;
}
public void InitializeViews() {
listView = (ListView) rootview.findViewById(R.id.menu_items_list);
Bundle bundle = getArguments();
menuheadingDetailList = bundle.getParcelableArrayList(AppConstants.MENU_KEY);
listView.setAdapter(new MenuAdapter(getActivity(), menuheadingDetailList));[enter image description here][1]
This is"MenuPagerAdapter" class
public class MenuPagerAdapter extends FragmentStatePagerAdapter {
List<MenuModel> menu;
public MenuPagerAdapter(FragmentManager fm, List<MenuModel> menuList) {
super(fm);
this.menu = menuList;
}
#Override
public CharSequence getPageTitle(int position) {
return menu.get(position).getHeading().toString();
}
private List<MenuHeadingDetailsModel> getMenuHeadingDetails(int pos) {
return this.menu.get(pos).getMenuHeadingDetailList();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new MenuDetailFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(AppConstants.MENU_KEY, (ArrayList<? extends Parcelable>) getMenuHeadingDetails(position));
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return menu.size();
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer == null) {
super.unregisterDataSetObserver(observer);
}
}
#Override
public void destroyItem (ViewGroup container, int position, Object object)
{
Log.e("destroyitem","called");
}
}
class MenuAdapter extends BaseAdapter {
//ViewHolder holder;
Context context;
List<MenuHeadingDetailsModel> myItems = new ArrayList<>();
Button buttonPlus, buttonMinus;
int totalAmount = 0;
int pagePosition;
public MenuAdapter(Context context, List<MenuHeadingDetailsModel> myItems) {
this.context = context;
this.myItems = myItems;
}
#Override
public int getCount() {
return myItems.size();
}
#Override
public Object getItem(int position) {
return myItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder = new ViewHolder();
final LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.menu_list_item, null);
viewHolder.codeText = (TextView) convertView.findViewById(R.id.textView_code);
viewHolder.nameText = (TextView) convertView.findViewById(R.id.textView_name);
AppMethods.setGlametrixBoldFont(getActivity(), viewHolder.nameText);
viewHolder.descText = (TextView) convertView.findViewById(R.id.textView_desc);
viewHolder.rateText = (TextView) convertView.findViewById(R.id.textView_rate);
viewHolder.textViewNoOfItems = (TextView) convertView.findViewById(R.id.tv_no_of_items);
buttonMinus = (Button) convertView.findViewById(R.id.button_minus);
buttonPlus = (Button) convertView.findViewById(R.id.button_plus);
final MenuHeadingDetailsModel menu = myItems.get(position);
viewHolder.codeText.setText(menu.getCode());
viewHolder.nameText.setText(menu.getItemName());
viewHolder.descText.setText(menu.getDescription());
viewHolder.rateText.setText(menu.getRate());
viewHolder.textViewNoOfItems.setText("" + menu.getQuantity());
buttonPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MenuHeadingDetailsModel menuList = myItems.get(position);
menuList.setQuantity(menuList.getQuantity() + 1);
myItems.set(position, menuList);
int itemRate = Integer.parseInt(myItems.get(position).getRate());
int itemQuan = menuList.getQuantity();
String code = menuList.getCode();
String name = menuList.getItemName();
int totalAmountPerItem = itemQuan * itemRate;
viewCartDetailsModel = new ViewCartDetailsModel(code, name, itemQuan, itemRate);
viewCartDetailsModelMap.put(viewCartDetailsModel.getCode(), viewCartDetailsModel);
Log.e("hashmap", "size" + viewCartDetailsModelMap.size());
Gson gson = new Gson();
String hashMapToString = gson.toJson(viewCartDetailsModelMap);
AppPreferences.saveDataInSharedpreferences(getActivity(), AppConstants.VIEW_ITEMS_INT_CART_KEY, hashMapToString);
totalAmount += itemRate;
int amount = totalAmount;
onButtonPressedForAmount(amount);
notifyDataSetChanged();
int quan = 0;
TextView tv;
for (int i = 0; i < listView.getCount(); i++) {
View view = listView.getAdapter().getView(i, null, null);
tv = (TextView) view.findViewById(R.id.tv_no_of_items);
quan = quan + Integer.parseInt(tv.getText().toString());
}
onButtonClickedForQuantity(quan);
}
}
);
buttonMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MenuHeadingDetailsModel menuList = myItems.get(position);
if ((menuList.getQuantity() - 1) >= 0) {
menuList.setQuantity(menuList.getQuantity() - 1);
myItems.set(position, menuList);
int itemRate = Integer.parseInt(myItems.get(position).getRate());
int itemQuan = menuList.getQuantity();
String code = menuList.getCode();
String name = menuList.getItemName();
//int totalAmountPerItem = itemQuan * itemRate;
viewCartDetailsModel = new ViewCartDetailsModel(code, name, itemQuan, itemRate);
if (itemQuan == 0) {
viewCartDetailsModelMap.remove(code);
} else {
viewCartDetailsModelMap.put(viewCartDetailsModel.getCode(), viewCartDetailsModel);
}
Gson gson = new Gson();
String hashMapToString = gson.toJson(viewCartDetailsModelMap);
AppPreferences.saveDataInSharedpreferences(getActivity(), AppConstants.VIEW_ITEMS_INT_CART_KEY, hashMapToString);
if (totalAmount > 0) {
totalAmount -= itemRate;
Log.e("totalamount", "minus" + totalAmount);
int amount = totalAmount;
onButtonPressedForAmount(amount);
}
} else {
menuList.setQuantity(0);
myItems.set(position, menuList);
}
notifyDataSetChanged();
int quan = 0;
TextView tv;
for (int i = 0; i < listView.getCount(); i++) {
View view = listView.getAdapter().getView(i, null, null);
tv = (TextView) view.findViewById(R.id.tv_no_of_items);
quan = quan + Integer.parseInt(tv.getText().toString());
}
onButtonClickedForQuantity(quan);
}
}
);
return convertView;
}
public void onButtonPressedForAmount(int userData) {
if (comm != null) {
comm.sendAmount(userData);
}
}
public void onButtonClickedForQuantity(int quantity) {
if (comm != null) {
comm.sendQuantity(quantity);
}
}
class ViewHolder {
TextView nameText;
TextView codeText;
TextView descText;
TextView rateText;
TextView textViewNoOfItems;
}
}
//For settings fonts to the alert diaolog for customization of items
//public void setGlametrixBoldFont(TextView textView) {
//Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/GlametrixBold.otf");
//textView.setTypeface(typeface);
// }
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
comm = (Communicate) activity;
} catch (Exception e) {
AppMethods.getStackTrace(e);
}
}
public interface Communicate {
public void sendAmount(int amount);
public void sendQuantity(int quantity);
}
// public void getPosition(int Position) {
//
// int pagePosition = Position;
// Log.e("pos", " " + pagePosition);
// }
}
You can get your current fragment inside view pager by following below way
SampleFragment sampleFr = (SampleFragment) viewPager.getAdapter().instantiateItem(viewPager, 0);
Now you can access any data you want using that fragment.
For the first time adding fragments in view pager do like below way.
BaseFragment frTimeLine = (BaseFragment) Fragment.instantiate(this, SampleFragment.class.getName());
fragments.add(frTimeLine);
BaseFragment frEarnTiqs = (BaseFragment) Fragment.instantiate(this, SampleFragment1.class.getName());
fragments.add(frEarnTiqs);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), getResources(), fragments);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);

changing items in recyclerview adapter

I inserted/removing from particular position in ArrayList onBindViewHolder . Now , i want to show this modified list on recyclerview .
Adapter Code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyAdapterViewHolder> {
private List<Info> dataList;
private Context mAct;
private List<Info> totalCandidatesList;
private String TAG = "OWD";
public MyAdapter(List<Info> dataList, Context context) {
this.dataList = dataList;
this.mAct = context;
}
public void addApplications(List<Info> candidates) {
if(this.totalCandidatesList == null){
totalCandidatesList = new ArrayList<>();
}
this.dataList.addAll(candidates);
this.totalCandidatesList.addAll(candidates);
this.notifyItemRangeInserted(0, candidates.size() - 1);
}
public void clearApplications() {
int size = this.dataList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
dataList.remove(0);
totalCandidatesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public int getItemCount() {
return dataList.size();
}
public void onBindViewHolder(MyAdapterViewHolder mAdapterViewHolder, int i) {
if (i % 2 == 1) {
mAdapterViewHolder.cardView.setCardBackgroundColor(Color.parseColor("#ecf5fe"));
mAdapterViewHolder.layoutRipple.setBackgroundColor(Color.parseColor("#ecf5fe"));
} else {
mAdapterViewHolder.cardView.setCardBackgroundColor(Color.parseColor("#e2f1ff"));
mAdapterViewHolder.layoutRipple.setBackgroundColor(Color.parseColor("#e2f1ff"));
}
final WorkHolders workHolders = SingleTon.getInstance().getWorkHolders();
final String customerName = SingleTon.getInstance().getCustomerName();
String siteName = null;
if(customerName !=null) {
String[] sitenamearray = customerName.split("--");
if (sitenamearray.length > 1) {
siteName = sitenamearray[1];
}
}
final Info ci = dataList.get(i);
mAdapterViewHolder.title.setText(ci.heading1);
mAdapterViewHolder.jobNumber.setText(ci.heading2);
mAdapterViewHolder.distance.setText(ci.distance);
if(siteName != null && siteName.equalsIgnoreCase(ci.heading2)) {
mAdapterViewHolder.cardView.setCardBackgroundColor(Color.parseColor("#a7ffeb"));
mAdapterViewHolder.layoutRipple.setBackgroundColor(Color.parseColor("#a7ffeb"));
if(i!=0){
> //Here i removed and inserted item in list .
> dataList.remove(i);
> dataList.add(0,ci);
}
}
final String finalSiteName = siteName;
final Bundle bundle = new Bundle();
mAdapterViewHolder.layoutRipple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
String name = ci.heading1 + "--" + ci.heading2;
Log.d(TAG,"new Jobname : "+ name);
if (finalSiteName == null || finalSiteName.equalsIgnoreCase("")) {
bundle.putString("name", customerName);
bundle.putString("oldwork", "yes");
bundle.putString("running_job_selected", "yes");
} else {
Log.d(TAG,"StartedOn Before Sending Bundle :" + workHolders.startedOn);
Log.d(TAG, "running Job is not selected");
bundle.putString("name", name);
bundle.putString("oldwork", "yes");
bundle.putString("running_job_selected", "no");
}
FragmentTransaction ft = ((FragmentActivity) mAct).getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.glide_fragment_horizontal_in, R.anim.glide_fragment_horizontal_out);
fragment = new WorkDescriptionFragment();
fragment.setArguments(bundle);
ft.addToBackStack("myadapter");
ft.replace(R.id.content_frame, fragment).commit();
SingleTon.getInstance().setWorkStatus("start");
}
});
}
#Override
public MyAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.single_item1, viewGroup, false);
return new MyAdapterViewHolder(itemView);
}
public static class MyAdapterViewHolder extends RecyclerView.ViewHolder {
protected TextView title;
protected TextView dateTime;
protected TextView distance;
protected TextView jobNumber;
protected CardView cardView;
protected LayoutRipple layoutRipple;
public MyAdapterViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.title);
dateTime = (TextView) v.findViewById(R.id.dateTimeTextView);
distance = (TextView) v.findViewById(R.id.distanceTextView);
jobNumber = (TextView) v.findViewById(R.id.jobNumber);
cardView = (CardView) v.findViewById(R.id.cv);
layoutRipple = (LayoutRipple)v.findViewById(R.id.singleitemripple);
}
}
}
you will see following lines in above code where i am removing/inserting item in a list onBindview and would like to show same in recyclerview .
But right now i am getting normal datalist(unchanged) .
//Here i removed and inserted item in list .
dataList.remove(i);
dataList.add(0,ci);
Please help me to achieve this .
onBindViewHolder is not the place where you should update your adapter. The staregy is to update item inside your Adapter data list and then notifyDataChanged(). For example thise are the methods for updating info inside my adapter:
public void update(Track track) {
tracks.remove(track);
add(track);
}
public void add (Track track) {
tracks.add(track);
this.notifyDataSetChanged();
}
public void addTracks(List<Track> tracks){
this.tracks.addAll(tracks);
this.notifyDataSetChanged();
}
public void clearAndAddTracks(List<Track> tracks) {
for (int i = 0; i < this.tracks.size(); i++) {
if (!this.tracks.get(i).isRunning()){
}
}
this.tracks.clear();
this.tracks.addAll(tracks);
this.notifyDataSetChanged();
}

Fragment is not refreshing after button clicked in adapter-listview

I have five tabs they are 1.home 2.menu 3.cart 4.account 5.more.Here cart tab consist of list view which is having the remove button in it,when i click on that remove button it must refresh the fragment itself so that it can load new data from the Json
MainActivity.class
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Session cartsession=new Session(getApplicationContext());
if (cartsession.isLoggedIn()){
if (position==2){
((Cart) pageAdapter.getItem(position)).cartdata();
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
}
TabAdapter.class
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Cart.Java
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
SharedPreferences loginPreferences;
SharedPreferences.Editor loginPrefsEditor;
TextView cartstatus,cartempty;
LinearLayout linearlay;
RelativeLayout cartvisible;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartstatus = (TextView) cartfrag.findViewById(R.id.cartstatus);
cartempty = (TextView) cartfrag.findViewById(R.id.cartempty);
linearlay = (LinearLayout) cartfrag.findViewById(R.id.linearlay);
cartvisible = (RelativeLayout) cartfrag.findViewById(R.id.cartvisible);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged = new Session(getActivity());
if (cartlogged.isLoggedIn()) {
cartitems.clear();
cartdata();
} else {
cartstatus.setText("Please Login");
}
return cartfrag;
}
void cartdata() {
cartitems.clear();
SharedPreferences customerid = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid = customerid.getString("customerid", "");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("empty")) {
cartstatus.setVisibility(View.GONE);
cartempty.setText("Your Cart is Empty");
} else {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
linearlay.setVisibility(View.VISIBLE);
cartvisible.setVisibility(View.GONE);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
JSONObject subobj = response.getJSONObject("details");
String subtext = subobj.getString("subtotal");
loginPrefsEditor.putString("Price", subtext);
loginPrefsEditor.commit();
subtotal.setText(subtext);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}
CartAdapter.class
public class CartAdapter extends BaseAdapter {
Context context;
TextView quantity, basenamecart, cartprice;
ImageButton delete;
private List<JSONParser> cartitems;
LayoutInflater inflater;
String removequantity, removeitemprice,removebasename;
public CartAdapter(Context context, List<JSONParser> cartitems) {
this.context = context;
this.cartitems = cartitems;
}
#Override
public int getCount() {
return cartitems.size();
}
#Override
public Object getItem(int position) {
return cartitems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart();
}
});
}
return convertView;
}
private void removecart(){
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
}
You need to remove the concerned object from the list cartitems and then call the notifyDataSetChanged() method to notify the any dependent views to refresh itself.
Documentation here
Also, this is not the correct way to implement a BaseAdapter and handle changes in it. Maybe this will help : http://androidadapternotifiydatasetchanged.blogspot.in/
Also, try using the new RecyclerView in order to implement such things. It is available in the support library and definitely a good way to display collections and also makes it easy to add remove items with default animations too. Please read through it. A starting point http://developer.android.com/training/material/lists-cards.html
see added line and updated line.
add make sure only remove item from list if removed successfully from server.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
final int pos =position; // added line
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart(pos); //updated line
}
});
}
return convertView;
}
public void updateCartitems(List<JSONParser> newCartitems) {
cartitems.clear();
cartitems.addAll(newCartitems);
this.notifyDataSetChanged();
}
private void removecart(int pos){ // updated line
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
cartitems.remove(pos); //added line
updateCartitems(cartitems);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}

How to put values from a textview in a row of a listview to a fragment

Working on android app' and I want to pass value from my textview that is in a row of a listview and put it in a fragment. I hear about convertView.gettag and settag method put I don't know how to deal with.
My code:
public class EvaluationsFragment extends CustomFragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private Patient mPatient;
private View myView;
private Context context;
private Button btnAjoutEvaluation;
private ListView evaluations_historic_liste;
private List<Evaluation>mEvaluation;
private EvaluationDto mEvaluationDto;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_evaluations, container,false);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
init();
}
private void init(){
evaluations_historic_liste = (ListView)myView.findViewById(R.id.evaluations_historic_liste);
btnAjoutEvaluation = (Button)myView.findViewById(R.id.evaluations_add__btn);
btnAjoutEvaluation.setOnClickListener(this);
TypeEvaluation mNouveauTypeEvaluation;
mPatient =((DossierActivity)mRootActivity).mPatient;
mEvaluationDto = new EvaluationDto(mRootActivity.getApplicationContext());
evaluations_historic_liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EvaluationAdapter.EvaluationItem item = (EvaluationAdapter.EvaluationItem)view.getTag();
openDetailEvaluation(item);
}
});
mEvaluationDto.open();
try{
mEvaluation = mEvaluationDto.getEvaluationsByPatientId(mPatient.getId());
}catch (SQLException e) {
Log.e(Constants.APP_LOG_TAG, e.getMessage());
ACRA.getErrorReporter().handleException(e);
} finally{
mEvaluationDto.close();
}
if(mEvaluation != null && mEvaluation.size() >0){
evaluations_historic_liste.setAdapter(new EvaluationAdapter(mRootActivity,mEvaluation));
}else {
evaluations_historic_liste.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case (R.id.evaluations_add__btn):
openNewEvaluation();
break;
}
}
public void openNewEvaluation(){
Fragment fragment = new EvaluationNouvelleFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new EvaluationNouvelleFragment());
fragmentTransaction.commit();
}
public void openDetailEvaluation(EvaluationAdapter.EvaluationItem item){
EvaluationAdapter evaluationAdapter = new EvaluationAdapter();
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle args = new Bundle();
args.putString(EvaluationDetailHistoriqueFragment.DATA_RECEIVE, /*HERE I NEED TO PUT item_evaluation_nom.setText()*/ );
detail.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, detail).commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class EvaluationAdapter extends BaseAdapter {
private Context mcontext;
private List<EvaluationItem> mItems = new ArrayList<EvaluationItem>();
public EvaluationAdapter(){}
public EvaluationAdapter(Context context, List<Evaluation> values) {
this.mcontext = context;
for (Evaluation e : values) {
mItems.add(new EvaluationItem(e));
}
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public EvaluationItem getItem(int position) {
return mItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
EvaluationItemHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mcontext).inflate(R.layout.list_items_historic_evaluations, parent, false);
holder = new EvaluationItemHolder();
holder.item_evaluation_date = (TextView) convertView.findViewById(R.id.item_evaluation_date);
holder.item_evaluation_nom = (TextView) convertView.findViewById(R.id.item_evaluation_nom);
holder.item_evaluation_personnel = (TextView) convertView.findViewById(R.id.item_evaluation_personnel);
holder.item_evaluation_score = (TextView) convertView.findViewById(R.id.item_evaluation_score);
holder.item_evaluation_date_reevaluation = (TextView) convertView.findViewById(R.id.item_evaluation_date_reevaluation);
convertView.setTag(holder);
}else{
holder = (EvaluationItemHolder)convertView.getTag();
}
final EvaluationItem item = getItem(position);
int score = (item.getScoreTV()).intValue();
holder.item_evaluation_date.setText( + " " + item.getDateTV());
holder.item_evaluation_nom.setText(item.getTypeEvalTV());
if (item.getPersonnelTV() != null) {
holder.item_evaluation_personnel.setText( + " " + item.getPersonnelTV());
}
holder.item_evaluation_score.setText( + String.valueOf(score));
if (item.getDateReevalTV() != null) {
holder.item_evaluation_date_reevaluation.setText( item.getDateReevalTV());
}
// convertView.setTag(1,item.getTypeEvalTV());
return convertView;
}
public class EvaluationItem {
private String dateTV;
private String typeEvalTV;
private String personnelTV;
private Double scoreTV;
private String dateReevalTV;
public String getDateTV() {return dateTV;}
public void setDateTV(String dateTV) {
this.dateTV = dateTV;
}
public String getTypeEvalTV() {
return typeEvalTV;
}
public void setTypeEvalTV(String typeEvalTV) {
this.typeEvalTV = typeEvalTV;
}
public String getPersonnelTV() {
return personnelTV;
}
public void setPersonnelTV(String personnelTV) {
this.personnelTV = personnelTV;
}
public Double getScoreTV() {
return scoreTV;
}
public void setScoreTV(Double scoreTV) {
this.scoreTV = scoreTV;
}
public String getDateReevalTV() {
return dateReevalTV;
}
public void setDateReevalTV(String dateReevalTV) {
this.dateReevalTV = dateReevalTV;
}
public EvaluationItem(Evaluation e){
this.dateTV = e.getDate();
this.typeEvalTV = e.getTypeEvaluation().getLibelle();
this.personnelTV = e.getPersonnelLibelle();
this.scoreTV = e.getScore();
this.dateReevalTV = e.getDateReevaluation();
}
}
}
public static class EvaluationItemHolder{
public TextView item_evaluation_date;
public TextView item_evaluation_nom;
public TextView item_evaluation_personnel;
public TextView item_evaluation_score;
public TextView item_evaluation_date_reevaluation;
}
}
You were doing good, you need a Bundle to do this.
First of all create a String where you can keep the value of
holder.item_evaluation_nom.getText();
Then for example you do this :
String itemEvaluation = holder.item_evaluation_nom.getText();
This is the correct Bundle
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle bundle = new Bundle();
bundle.putString("text", itemEvaluation);
detail.setArguments(bundle);
Then to retrieve this you do this :
Bundle bundle = this.getArguments();
if (bundle != null) {
String itemEvaluation = bundle.getString("text", "");
}
hope it helps.
EDIT
You'll need to add an Adapter to your evaluations_historic_liste list.
You can do this doing :
evaluations_historic_liste.setAdapter(new EvaluationAdapter(getActivity(),mEvaluation));
mEvaluation is the List that you have to put data on it.
Then in your ListView add this :
evaluation_historic_liste.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id){
String itemEvaluation = (String) ((TextView)view.findViewById(R.id.item_evaluation_nom)).getText();
//or
String itemEvaluation=(evaluation_historic_liste.getItemAtPosition(position).toString());
}
}

ListView in ListFragment keeps accumulating data

I am unable to refresh my ListView in ListFragment with new data. Instead the new data is added to the previous.
The time period is from 6AM to 5PM for each entity. Then new data is appended to the list restarting at 6AM for another entity. The data for the first entity should be cleaned before the second is added to the ListView.
Here is the code:
public class FragmentStatePagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 4; //control number of fragments
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(null);
mPager.setAdapter(mAdapter);
}
//===============================================================================================
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
fragNumber = position;
return ArrayListFragment.newInstance(position);
}
}
//===============================================================================================
public static class ArrayListFragment extends ListFragment {
Integer mNum;
String FORMAT_LINE = "%s%7s%7s%10s%16s";
static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
View tv = v.findViewById(R.id.text);
View tvd = v.findViewById(R.id.tv_description);
String title = "";
switch (mNum){
case 0:title = MyGlobals.getInstance().getToday();break;
case 1:title = MyGlobals.getInstance().getTomorrow();break;
case 2:title = MyGlobals.getInstance().getDayAfter();break;
case 3:title = MyGlobals.getInstance().getDayDayAfter();break;
}
((TextView) tv).setText(MyGlobals.getInstance().getName() + " on " + title);
((TextView) tvd).setText(String.format(FORMAT_LINE, "time", "temp", "rain", "wind", "weather"));
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<Data> row = Data.getRows(mNum);
ListViewAdapter adapter = new ListViewAdapter(getActivity(), row);
getListView().setAdapter(null);
getListView().setAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
v.setBackgroundColor(getResources().getColor(R.color.blue));
}
}
//==============================================================================================
public static class ListViewAdapter extends ArrayAdapter<Data> {
public static class ViewHolder{
TextView time;
TextView temp;
TextView rain;
TextView wind_speed;
TextView weather;
}
public ListViewAdapter(Context context, ArrayList<Data> list) {super(context, R.layout.text_listview, list); }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Data data = getItem(position);
ViewHolder holder;
if(convertView == null){
holder=new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView=inflater.inflate(R.layout.text_listview,parent,false);
holder.time=(TextView) convertView.findViewById(R.id.time);
holder.temp=(TextView) convertView.findViewById(R.id.temp);
holder.rain=(TextView) convertView.findViewById(R.id.rain);
holder.wind_speed=(TextView) convertView.findViewById(R.id.wind);
holder.weather=(TextView) convertView.findViewById(R.id.weather);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
holder.time.setText(data.time);
holder.temp.setText(data.temp);
holder.rain.setText(data.rain);
holder.wind_speed.setText(data.wind_speed);
holder.weather.setText(data.weather);
return convertView;
}
}
}
This last piece populates the ListView. The calls adapter.clear() and adapter.notifyDataSetChanged() does not resolve the problem.
There is a similar question from 3 years ago How update ListView in ListFragment from FragmentActivity? still without accepted response despite the 6836 views.
Thanks a Lot.
The GetRows(mNum) piece as requested:
public class Data {
public String time;
public String temp;
public String rain;
public String wind_speed;
public String weather;
public Data(String time, String temp, String rain, String wind_speed, String weather) {
this.time = time;
this.temp = temp;
this.rain = rain;
this.wind_speed = wind_speed;
this.weather = weather;
}
public static ArrayList<Data> getRows(int fragNumber) {
int mNum = fragNumber;
int size;
String myList[] = null;
ArrayList<Data> list = new ArrayList<Data>();
switch (mNum) {
case 0://Today
size = MyGlobals.getInstance().getToday("time").size();
myList = new String[size];
for (int i = 0; i < size; i++) {
String time = (String) MyGlobals.getInstance().getToday("time").get(i);
String temp = (String) MyGlobals.getInstance().getToday("temperature").get(i);
String wind_speed = (String) MyGlobals.getInstance().getToday("wind_speed").get(i);
String pop = (String) MyGlobals.getInstance().getToday("pop").get(i);
//String wind_gust = (String) MyGlobals.getInstance().getToday("wind_gust").get(i); //when null breaks code
String weather = (String) MyGlobals.getInstance().getToday("weather").get(i);
if (time.length() == 4) time = "0" + time;
if (wind_speed.length() == 1) wind_speed = "0" + wind_speed;
if (pop.length() == 1) pop = "0" + pop;
list.add(new Data(time,temp,pop,wind_speed,weather));
}
return list;
case 1://Tomorrow
...snip... same as above with pertinent variables,...
case 2://DayAfter
...snip...
case 3://DayDayAfter
...snip....
case 4:// is an error
Log.d("***error***", "list got to case 5");
}
return list;
}
}
Try this;
Before adding new list of Data to the existing list, use list.clear();
Add new Data to the list and you should have only newly added data in the list..
pass the list to your adapter class.
Notify adapter of the new data i.e. adapter.notifyDataSetChanged()
You are returning list twice in your getRows()
remove the "return list" before the case structure
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Clear old list here before adding new one.
if (list! = null)
{
list.clear();
}
// Add New list
list = Data.getRows(mNum);
ListViewAdapter adapter = new
ListViewAdapter(getActivity(), list);
getListView().setAdapter(adapter);
adapter.notifyDataSetChange();
}
It's because everytime you set an Adapter, it will really be added., remove all its data first before setting again so it will be like
mPager.setAdapter(null);
before doing
mPager.setAdapter(mAdapter);

Categories

Resources