I have a tabbed fragment outlined by the class below.
There are two tabs with lists of information, Friends and Groups. The issue I am having, is that the Group list renders first within the Friends tab, then disappears allowing the Friends list to render within the Friends tab. However, the upon swiping to the Groups tab, the groups list never renders.
How can this be resolved?
Tabbed Activity:
public class InvitingFriendsGroupsToEvents extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inviting_friends_groups_to_events);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_inviting_friends_groups_to_events, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_inviting_friends_groups_to_events, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
// Need to build
// Order/first appearing will be specific to time of day, ie. if in morning, then breakfast/brunch, if midday then lunch, late then dinner
switch (position) {
case 0:
return new InviteFriendsToEventsFragment();
case 1:
return new InviteGroupsToEventsFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Friends";
case 1:
return "Groups";
}
return null;
}
}
}
Friend Tab:
public class InviteFriendsToEventsFragment extends Fragment {
// ie. once a fiend is invited, it will show their group on the second tab, the name, who invite them
MyCustomAdapter dataAdapter = null;
SaveSharedPreference preference = new SaveSharedPreference();
final Firebase myFeastFirebase = new Firebase(Constants.getFirebaseUrl());
Firebase presentEventMembers;
Firebase myFriends;
Firebase sentFriendEventInvites; // this will be the grayed out standing invitation
Firebase eventMemberInviteNeedSync;
ValueEventListener getFriendsListener;
ValueEventListener getEventMembersListener;
ValueEventListener getAlreadyInvitedFriendsListener;
String eventID;
String eventName;
ArrayList<Member> mEventMembers = new ArrayList<>();
ArrayList<Member> mFriends = new ArrayList<>();
ArrayList<Member> mAlreadyInvited = new ArrayList<>();
ArrayList<FriendInvite> mFriendsFinalInviteStatuses = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.invite_friends_to_events, container, false);
Bundle extras = getActivity().getIntent().getExtras();
eventID = extras.getString("eventID");
eventName = extras.getString("eventName");
Log.v("InvitingFriendsToEvents", "Event ID: " + eventID);
Log.v("InvitingFriendsToEvents", "Event Name" + eventName);
//Generate list View from ArrayList
// Get present group members
presentEventMembers = myFeastFirebase.child("eventMembers").child(eventID);
myFriends = myFeastFirebase.child("friends").child(preference.getUserSyncID(getContext()));
sentFriendEventInvites = myFeastFirebase.child("userEventMemberInviteSent").child(preference.getUserSyncID(getContext())).child(eventID);
eventMemberInviteNeedSync = myFeastFirebase.child("eventMemberInviteNeedSync");
getAlreadyInvitedFriendsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot inviteSnapshot : dataSnapshot.getChildren()) {
Member invitedFriend = new Member();
invitedFriend.setUserUID(inviteSnapshot.getKey());
invitedFriend.setUserName(inviteSnapshot.getValue().toString());
mAlreadyInvited.add(invitedFriend);
Log.v("InvitingFriendsToEvents", "Invite Sent userName is: " + inviteSnapshot.getValue().toString());
Log.v("InvitingFriendsToEvents", "Invite Sent ID is: " + inviteSnapshot.getKey().toString());
}
// Here will be the operation to get the proper setting for
// First: remove from friends, those already in the group:
mFriends.removeAll(mEventMembers);
// Then add to the invite group
for (Member friend : mFriends) {
FriendInvite groupMemberInvite = new FriendInvite();
groupMemberInvite.setUserName(friend.getUserName());
groupMemberInvite.setUserUID(friend.getUserUID());
if (mAlreadyInvited.contains(friend)) {
groupMemberInvite.setInvitedAlready(true);
}
mFriendsFinalInviteStatuses.add(groupMemberInvite);
Log.v("InvitingFriendsToEvents", "Final List UserName is: " + groupMemberInvite.getUserName());
Log.v("InvitingFriendsToEvents", "Final List UserID is: " + groupMemberInvite.getUserUID());
Log.v("InvitingFriendsToEvents", "Final List InviteStatus is: " + groupMemberInvite.isInvitedAlready());
}
//dataAdapter.notifyDataSetChanged();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, mFriendsFinalInviteStatuses);
ListView listView = (ListView) getActivity().findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
getFriendsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendSnapshot : dataSnapshot.getChildren()) {
if (!friendSnapshot.getKey().equals(preference.getUserSyncID(getContext()))) {
Member friend = new Member();
friend.setUserUID(friendSnapshot.getKey());
friend.setUserName(friendSnapshot.child("userName").getValue().toString());
mFriends.add(friend);
Log.v("InvitingFriendsToEvents", "Friend userName is: " + friendSnapshot.child("userName").getValue().toString());
Log.v("InvitingFriendsToEvents", "Friend user ID is: " + friendSnapshot.getKey().toString());
}
}
// after getting friends
sentFriendEventInvites.addListenerForSingleValueEvent(getAlreadyInvitedFriendsListener);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.v("InvitingFriendsToEvents", "Firebase Error: " + firebaseError.toString());
}
};
getEventMembersListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot groupMemberSnapshot : dataSnapshot.getChildren()) {
if (!groupMemberSnapshot.getKey().equals(preference.getUserSyncID(getContext()))) {
Member groupMember = new Member();
groupMember.setUserUID(groupMemberSnapshot.getKey());
groupMember.setUserName(groupMemberSnapshot.getValue().toString());
mEventMembers.add(groupMember);
Log.v("InvitingFriendsToEvents", "Group member userName is: " + groupMemberSnapshot.getValue().toString());
Log.v("InvitingFriendsToEvents", "Group member user ID is: " + groupMemberSnapshot.getKey().toString());
}
}
// upon completion of getting groups
myFriends.addListenerForSingleValueEvent(getFriendsListener);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.v("InvitingFriendsToEvents", "Firebase Error: " + firebaseError.toString());
}
};
presentEventMembers.addListenerForSingleValueEvent(getEventMembersListener);
//confirmFriendInvites();
return view;
}
private class MyCustomAdapter extends ArrayAdapter<FriendInvite> {
private ArrayList<FriendInvite> groupMemberInviteList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<FriendInvite> groupMemberInviteList) {
super(context, textViewResourceId, groupMemberInviteList);
this.groupMemberInviteList = new ArrayList<>();
this.groupMemberInviteList.addAll(groupMemberInviteList);
}
private class ViewHolder {
TextView inviteSent;
CheckBox checkBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1); // here it is
holder.inviteSent = (TextView) convertView.findViewById(R.id.invite_already_sent);
convertView.setTag(holder);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
FriendInvite groupMemberInivited = (FriendInvite) cb.getTag();
Toast.makeText(getActivity(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
groupMemberInivited.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
FriendInvite groupMemberInvite = groupMemberInviteList.get(position);
holder.checkBox.setText(groupMemberInvite.getUserName());
holder.checkBox.setChecked(groupMemberInvite.isSelected());
holder.checkBox.setTag(groupMemberInvite);
// Check if already invited, if so, should remove
if (groupMemberInvite.isInvitedAlready() == true) {
holder.checkBox.setTextColor(Color.GRAY);
holder.checkBox.setClickable(false);
holder.inviteSent.setText("Invite Already Sent");
} else {
holder.inviteSent.setText("");
}
return convertView;
}
}
}
Group Tab:
public class InviteGroupsToEventsFragment extends Fragment {
// ie. once a fiend is invited, it will show their group on the second tab, the name, who invite them
GroupInviteCustomAdapter dataAdapter = null;
SaveSharedPreference preference = new SaveSharedPreference();
final Firebase myFeastFirebase = new Firebase(Constants.getFirebaseUrl());
Firebase presentEventMembers;
Firebase sentFriendEventInvites; // this will be the grayed out standing invitation
Firebase mGroups;
Firebase mGroupMembers;
Firebase eventMemberInviteNeedSync;
ValueEventListener getFriendsListener;
ValueEventListener getEventMembersListener;
ValueEventListener getAlreadyInvitedFriendsListener;
ValueEventListener getUsersGroups;
String eventID;
String eventName;
ArrayList<Member> mEventMembers = new ArrayList<>();
ArrayList<Member> mFriends = new ArrayList<>();
ArrayList<Member> mAlreadyInvited = new ArrayList<>();
ArrayList<FriendInvite> mFriendsFinalInviteStatuses = new ArrayList<>();
ArrayList<GroupInvite> mUsersGroups = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.invite_groups_to_events, container, false);
Bundle extras = getActivity().getIntent().getExtras();
eventID = extras.getString("eventID");
eventName = extras.getString("eventName");
Log.v("InvitingFriendsToEvents", "Event ID: " + eventID);
Log.v("InvitingFriendsToEvents", "Event Name" + eventName);
//Generate list View from ArrayList
// Get present group members
presentEventMembers = myFeastFirebase.child("eventMembers").child(eventID);
mGroupMembers = myFeastFirebase.child("groupMembers"); // will append: .child("")
mGroups = myFeastFirebase.child("usersGroups").child(preference.getUserSyncID(getContext()));
sentFriendEventInvites = myFeastFirebase.child("userEventMemberInviteSent").child(preference.getUserSyncID(getContext())).child(eventID);
eventMemberInviteNeedSync = myFeastFirebase.child("eventMemberInviteNeedSync");
getUsersGroups = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot inviteSnapshot : dataSnapshot.getChildren()) {
GroupInvite invitedGroup = new GroupInvite();
invitedGroup.setGroupSyncID(inviteSnapshot.getKey());
invitedGroup.setGroupName(inviteSnapshot.getValue().toString());
mUsersGroups.add(invitedGroup);
Log.v("InvitingFriendsToEvents", "Invite Sent userName is: " + inviteSnapshot.getValue().toString());
Log.v("InvitingFriendsToEvents", "Invite Sent ID is: " + inviteSnapshot.getKey().toString());
}
dataAdapter = new GroupInviteCustomAdapter(getActivity(),
R.layout.event_invites_groups, mUsersGroups);
ListView listView = (ListView) getActivity().findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
mGroups.addListenerForSingleValueEvent(getUsersGroups);
return view;
}
private class GroupInviteCustomAdapter extends ArrayAdapter<GroupInvite> {
private ArrayList<GroupInvite> groupInviteList;
public GroupInviteCustomAdapter(Context context, int textViewResourceId,
ArrayList<GroupInvite> groupInviteList) {
super(context, textViewResourceId, groupInviteList);
this.groupInviteList = new ArrayList<>();
this.groupInviteList.addAll(groupInviteList);
}
private class ViewHolder {
TextView inviteSent;
CheckBox checkBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.event_invites_groups, null);
holder = new ViewHolder();
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1); // here it is
holder.inviteSent = (TextView) convertView.findViewById(R.id.invite_already_sent);
convertView.setTag(holder);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
GroupInvite groupInvited = (GroupInvite) cb.getTag();
Toast.makeText(getActivity(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
groupInvited.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
GroupInvite groupInvite = groupInviteList.get(position);
holder.checkBox.setText(groupInvite.getName());
holder.checkBox.setChecked(groupInvite.isSelected());
holder.checkBox.setTag(groupInvite);
// Check if already invited, if so, should remove
if (groupInvite.isInvitedAlready() == true) {
holder.checkBox.setTextColor(Color.GRAY);
holder.checkBox.setClickable(false);
holder.inviteSent.setText("Invite Already Sent");
} else {
holder.inviteSent.setText("");
}
return convertView;
}
}
}
Move the below block of code outside getUsersGroups = new ValueEventListener()
dataAdapter = new GroupInviteCustomAdapter(getActivity(),
R.layout.event_invites_groups, mUsersGroups);
ListView listView = (ListView) getActivity().findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
ValueEventListener() only executes the override methods. My guess is that the above code never runs.Try and let me know if it works. If it doesnt will debug further.
Related
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")));
}
Well, I have recyclerView and a fragment as the examples of of Master Detail Flows
now i'm getting my data from json and i'm parsing it in the recyclerView perfectly
the problem is whenever I click on it I get null exception..
public class ItemDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private DummyContent.DummyItem mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
Activity activity = this.getActivity();
CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mItem.id);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.item_detail)).setText("hello");
}
return rootView;
}
and this is the Activity
public class ItemDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is where i get the json and ItemlistActivity
public class ItemListActivity extends AppCompatActivity {
View recyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
queue = Volley.newRequestQueue(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
connection();
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
String profilePicUrl = mValues.get(position).profile_pic;
String full_name = mValues.get(position).full_name;
String state = mValues.get(position).state;
String city = mValues.get(position).city;
String phoneNo = mValues.get(position).phone_no;
holder.full_name.setText("Name : " +full_name);
holder.state.setText("State : " +state);
holder.city.setText("City : " +city);
holder.phone_number.setText("Phone Number : " +phoneNo);
Glide.with(getApplicationContext())
.load(profilePicUrl)
.fitCenter()
.override(500,500)
.into(holder.profile_pic);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
Log.e("hello",holder.mItem.full_name);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void connection(){
final String url = "aaaaa";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject test = jsonArray.getJSONObject(i);
String gender = test.getString("gender");
String full_name = test.getJSONObject("name").getString("title") + " " +
test.getJSONObject("name").getString("first") + " " +
test.getJSONObject("name").getString("last");
String state = test.getJSONObject("location").getString("state");
String city = test.getJSONObject("location").getString("city");
String phone_no = test.getString("phone");
String profile_pic = test.getJSONObject("picture").getString("large");
String id = test.getJSONObject("id").getString("name");
Log.d("test2222", gender + " \n " + full_name + " \n " + state + " \n " + city + " \n " + phone_no + "\n" + profile_pic
+ "\n" + id);
addItem(new DummyContent.DummyItem(gender,profile_pic, full_name, state, city, phone_no,"hello"));
}
setupRecyclerView((RecyclerView) recyclerView);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
Toast.makeText(getApplicationContext(),"check internet connection",Toast.LENGTH_SHORT).show();
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
}
and at last dummycontent
public class DummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
}
public static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.full_name, item);
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String profile_pic;
public final String full_name;
public final String state;
public final String city;
public final String phone_no;
public final String data;
public DummyItem(String id ,String profile_pic, String full_name, String state ,String city,String phone_no,String data) {
this.id = id;
this.profile_pic = profile_pic;
this.full_name = full_name;
this.state = state;
this.city = city;
this.phone_no = phone_no;
this.data = data;
}
#Override
public String toString() {
return full_name;
}
}
}
now the thing is that I want to get same data (text or image) to the fragment
my problem is that I can't even show the fragment with custom "hello world" textview i get exception whenever I click on the recyclerview so explain to me where is the wrong in my code thanks
and this is the ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final ImageView profile_pic;
public final TextView full_name;
public final TextView state;
public final TextView city;
public final TextView phone_number;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
profile_pic = (ImageView) view.findViewById(R.id.profile_pic);
full_name = (TextView) view.findViewById(R.id.full_name_txt);
state = (TextView) view.findViewById(R.id.state_txt);
city = (TextView) view.findViewById(R.id.city_txt);
phone_number = (TextView) view.findViewById(R.id.phone_no_txt);
}
#Override
public String toString() {
return super.toString() + " '" + full_name.getText() + "'";
}
}
You are getting null value because you are using mItem from ViewHolder class without initializing, which is null.
Try this:
DummyContent.DummyItem mItem = mValues.get(position); //initialize here, not in ViewHolder class
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, mItem.id); //use without holder
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
Log.e("hello",holder.mItem.full_name);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, mItem.id); //same here
context.startActivity(intent);
}
}
});
My custom listview row has remove button. I'm trying to delete specific item in listview with this remove button. (Remove from favorites action). I can delete selected item but rest of the list (items under the selected item) deleting with it. Top part still stay. How can I fix this? Thanks in advance.
FavoriteListAdapter :
public class FavoritesListAdapter extends ArrayAdapter<String> {
private Activity context;
private List<String> radioName;
private List<String> listenerNumbers;
public FavoritesListAdapter(Activity context, List<String> radioName, List<String> listenerNumbers) {
super(context, R.layout.custom_favorites_listview, radioName);
this.context=context;
this.radioName=radioName;
this.listenerNumbers=listenerNumbers;
}
#NonNull
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View r= convertView;
FavoritesViewHolder viewHolder = null;
if (r == null) {
LayoutInflater layoutInflater= context.getLayoutInflater();
r= layoutInflater.inflate(R.layout.custom_favorites_listview,null,true);
viewHolder = new FavoritesViewHolder(r);
r.setTag(viewHolder);
}
else {
viewHolder = (FavoritesViewHolder) r.getTag();
}
viewHolder.row_tv_favorites_radio_name.setText(radioName.get(position));
viewHolder.row_img_favorites_radio_icon.setImageResource(R.drawable.radio_logo_renkli);
viewHolder.row_tv_favorites_listener_numbers.setText("Listeners : " + listenerNumbers.get(position));
viewHolder.button_remove_from_favorites_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listenerNumbers.remove(position);
radioName.remove(position);
SharedPreferences settings = context.getSharedPreferences("PREFS", 0);
final SharedPreferences.Editor editor = settings.edit();
editor.remove("radio_link"+ position);
editor.remove("radio_name" + position);
editor.remove("listener_number" + position);
// editor.clear();
editor.commit();
// FavoritesFragment.radio_name_list.remove(position);
// FavoritesFragment.radio_link_list.remove(position);
// FavoritesFragment.listener_numbers.remove(position);
notifyDataSetChanged();
}
});
return r;
}
class FavoritesViewHolder {
TextView row_tv_favorites_radio_name;
TextView row_tv_favorites_listener_numbers;
ImageView row_img_favorites_radio_icon;
Button button_remove_from_favorites_list;
FavoritesViewHolder(View v) {
row_tv_favorites_radio_name= (TextView) v.findViewById(R.id.txt_radio_name_favorites);
row_tv_favorites_listener_numbers = (TextView) v.findViewById(R.id.txt_listener_numbers_favorites);
row_img_favorites_radio_icon = (ImageView) v.findViewById(R.id.img_radio_icon_favorites);
button_remove_from_favorites_list = (Button) v.findViewById(R.id.remove_favorites_from_list_button);
}
}
}
In my PlayRadioFragment, users have add favorite button, and values sent FavoritesFragment with unique keys
public static int incrementedValue = 0;
SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
final SharedPreferences.Editor editor = settings.edit();
add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
add_favorites_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putString("radio_link"+ incrementedValue, radio_play_link);
editor.putString("radio_name" + incrementedValue, radio_name);
editor.putString("listener_number" + incrementedValue, listener_number);
// editor.clear();
editor.commit();
incrementedValue++;
}
});
And this is my FavoritesFragment :
public class FavoritesFragment extends Fragment {
public static FavoritesListAdapter adapter_2;
public FavoritesFragment() {
// Required empty public constructor
}
TextView radio_name_txt, radio_link_txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_favorites, container, false);
final List<String> radio_name_list = new ArrayList<>();
final List<String> radio_link_list = new ArrayList<>();
final List<String> listener_numbers = new ArrayList<>();
for (int i=0; i<Integer.MAX_VALUE; i++) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
String radio_name = settings.getString("radio_name" +i, "");
String radio_link = settings.getString("radio_link" +i, "");
String listener_number = settings.getString("listener_number" +i, "");
if (TextUtils.isEmpty(radio_name)){break;}
else {radio_name_list.add(radio_name);}
if (TextUtils.isEmpty(radio_link)){break;}
else {radio_link_list.add(radio_link);}
listener_numbers.add(listener_number);
}
PlayRadioFragment.incrementedValue = radio_name_list.size();
ListView listView_favorites = (ListView) view.findViewById(R.id.listview_favorites);
adapter_2 = new FavoritesListAdapter(getActivity(), radio_name_list, listener_numbers);
listView_favorites.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
PlayRadioFragment fragment= new PlayRadioFragment();
Bundle bundle= new Bundle();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("radio_play_links", radio_link_list.get(position));
bundle.putString("radio_name", radio_name_list.get(position));
bundle.putString("listener_number", listener_numbers.get(position));
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.frame_layout,fragment);
fragmentTransaction.commit();
}
});
listView_favorites.setAdapter(adapter_2);
return view;
}
Create Your Object class As:
public class DemoGson {
private String radio_link,radio_name,listener_number;
public String getRadio_link() {
return radio_link;
}
public void setRadio_link(String radio_link) {
this.radio_link = radio_link;
}
public String getRadio_name() {
return radio_name;
}
public void setRadio_name(String radio_name) {
this.radio_name = radio_name;
}
public String getListener_number() {
return listener_number;
}
public void setListener_number(String listener_number) {
this.listener_number = listener_number;
}
}
While Adding data to it create new object and add data then insert that particular object to arraylist and pass arraylist to your adapter
ArrayList<DemoGson> arrayList = new ArrayList<>();
DemoGson demoGson = new DemoGson();
demoGson.setRadio_link("yourlink");
demoGson.setRadio_name("yourname");
demoGson.setListener_number("2");
arrayList.add(demoGson);
and then
adapter_2 = new FavoritesListAdapter(getActivity(),arrayList);
and in adapter just remove position from your arraylist
This doesn't not remove element from the adapter, only from your custom arrays:
listenerNumbers.remove(position);
radioName.remove(position);
In additional, you need to remove the item from the internal ArrayList of the adapter. Do it like this:
remove(getItem(position));
Generally, it is not good approach to manage 2 parallel custom arrays in the adapter (listenerNumbers, radioName in your case). Better to define Item class, containing both those fields, and provide ArrayList of the objects of this class to adapter as parameter (instead of array of Strings like in your case). And also o implement supporting XML for the item, that will have both items (TextView and RadioButton).
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);
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);