Cannot Cast Activity to Interface in fragment - android

my code has Class Cast Exception error.
When the string is sent from the adapter to the fragment by interface. In the fragment, the interface goes to the specific activity if the particular string is selected.
this is Interface code:
public interface StringListener {
void sendStr(String title);
}
and so this is adapter code:
public class StringRecyclerViewAdapter extends RecyclerView.Adapter<StringRecyclerViewAdapter.MyViewHolder>{
List<GridSubject> subjects;
Context context;
public StringRecyclerViewAdapter(Context context,List<GridSubject> subjects)
{
this.context=context;
this.subjects=subjects;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater=LayoutInflater.from(context);
view=inflater.inflate(R.layout.custom_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
final GridSubject subject=subjects.get(position);
holder.txts.setText(subject.text);
holder.imgs.setImageResource(subject.drwab);
holder.myCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendStrMe(subject.getText());
}
});
}
#Override
public int getItemCount() {
return subjects.size();
}
public void sendStrMe(String title) {
StringListener listener=(StringListener) context;
listener.sendStr(title);
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView txts;
ImageView imgs;
CardView myCard;
public MyViewHolder(View itemView) {
super(itemView);
txts=itemView.findViewById(R.id.txt);
imgs=itemView.findViewById(R.id.img);
myCard=itemView.findViewById(R.id.my_card);
}
}
and this is Fragment Code:
public class FragmentA extends Fragment implements SportListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public Intent intent;
public FragmentA() {
// Required empty public constructor
}
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.my_layout_sport, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
try {
super.onActivityCreated(savedInstanceState);
RecyclerView recyclerView=getView().findViewById(R.id.recycler_me);
final String[] txts={"Special","Hard","Manual","Easy"};
int[] imgs={R.drawable.special,R.drawable.hard,R.drawable.manual,R.drawable.easy};
List<GridSubject> subjects=new ArrayList<>();
for(int i=0;i<imgs.length;i++) {
subjects.add(new GridSubject(txts[i], imgs[i]));
}
int ori=getResources().getConfiguration().orientation;
int span;
if(ori== Configuration.ORIENTATION_LANDSCAPE)
span=3;
else
span=2;
StringRecyclerViewAdapter adapter=new StringRecyclerViewAdapter(getActivity(),subjects);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),span));
recyclerView.setAdapter(adapter);
}
catch (Exception e)
{
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void sendSport(String title) {
if(title=="Special") {
intent=new Intent(getActivity(),WebActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
else{
intent=new Intent(getActivity(),SportShowActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
}
}
and this is Activity code:
public class MainActivity extends AppCompatActivity {
BottomNavigationView btm_navs;
FragmentA afrag;
FragmentB bfrag;
FragmentC cfrag;
FragmentD dfrag;
ViewPager pagerS;
MenuItem menuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btm_navs = findViewById(R.id.btn_navs);
pagerS = findViewById(R.id.view_pager_mes);
btm_navs.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.item_a:
pagerS.setCurrentItem(0);
break;
case R.id.item_b:
pagerS.setCurrentItem(1);
break;
case R.id.item_c:
pagerS.setCurrentItem(2);
break;
case R.id.item_d:
pagerS.setCurrentItem(3);
break;
}
return true;
}
});
pagerS.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (menuItem != null) {
menuItem.setChecked(false);
}
else {
btm_navs.getMenu().getItem(position).setChecked(false);
}
btm_navs.getMenu().getItem(position).setChecked(true);
menuItem = btm_navs.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setupViewPager();
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void setupViewPager()
{
ViewPageradapter pageradapter=new ViewPageradapter(getSupportFragmentManager());
afrag=new FragmentA();
bfrag=new FragmentB();
cfrag =new FragmentC();
dfrag=new FragmentD();
pageradapter.addFragment(afrag);
pageradapter.addFragment(bfrag);
pageradapter.addFragment(cfrag);
pageradapter.addFragment(dfrag);
pagerS.setAdapter(pageradapter);
}
}
and so these are errors:
java.lang.ClassCastException: com.example.project.MainActivity cannot be cast to com.example.project.StringListener
at com.example.pakhkhsh.StringRecyclerViewAdapter.sendStrMe(StringRecyclerViewAdapter.java:56)
at com.example.pakhkhsh.StringRecyclerViewAdapter$1.onClick(StringRecyclerViewAdapter.java:45)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Your activity needs to implement SportListener, not the fragment.
just do it:
public class MainActivity extends AppCompatActivity implements SportListener {
// your code ...
}```

Related

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

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

new value not inserted in my user interface when adding new object

I am trying to add an contact object and the way I do it is when the user hits add button in the menu bar; this is how I do it.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_contact:
Contact contact = new Contact();
ContactLab.get(getActivity()).addContact(contact);
updateUI();
mCallbacks.onContactSelected(contact);
return true;
case R.id.action_edit:
return true;
case R.id.action_delete:
ContactLab crimeLab = ContactLab.get(getActivity());
crimeLab.deleteContact(mContact);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I have the following fragment
public class ContactListFragment extends Fragment {
// private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
private static final String ARG_CRIME_ID = "crime_id";
private RecyclerView mCrimeRecyclerView;
private ContactAdapter mAdapter;
public Contact mContact;
private Callbacks mCallbacks;
/**
* Required interface for hosting activities.
*/
public interface Callbacks {
void onContactSelected(Contact contact);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallbacks = (Callbacks) context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.contact_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (savedInstanceState != null) {
}
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
private void updateSubtitle() {
ContactLab crimeLab = ContactLab.get(getActivity());
int contactCount = crimeLab.getContacts().size();
String subtitle = getString(R.string.subtitle_format, contactCount);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
public void updateUI() {
ContactLab crimeLab = ContactLab.get(getActivity());
List<Contact> contacts = crimeLab.getContacts();
if (mAdapter == null) {
mAdapter = new ContactAdapter(contacts);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setContacts(contacts);
mAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
private class ContactHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private TextView mTitleTextView;
public ContactHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_content, parent, false));
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.content_name);
}
public void bind(Contact contact) {
mContact = contact;
mTitleTextView.setText(mContact.getName());
}
#Override
public void onClick(View view) {
mCallbacks.onContactSelected(mContact);
}
}
private class ContactAdapter extends RecyclerView.Adapter<ContactHolder> {
private List<Contact> mContacts;
public ContactAdapter(List<Contact> crimes) {
mContacts = crimes;
}
#Override
public ContactHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new ContactHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(ContactHolder holder, int position) {
Contact contact=mContacts.get(position);
holder.bind(contact);
}
#Override
public int getItemCount() {
return mContacts.size();
}
public void setContacts(List<Contact> contacts) {
mContacts = contacts;
}
}
and then I start the above fragment from the following activity fragment
public class ContactListActivity extends SingleFragmentActivity
implements ContactListFragment.Callbacks, ContactFragment.Callbacks {
#Override
protected Fragment createFragment() {
return new ContactListFragment();
}
#Override
protected int getLayoutResId() {
return R.layout.activity_masterdetail;
}
#Override
public void onContactSelected(Contact contact) {
if (findViewById(R.id.detail_fragment_container) == null) {
Intent intent = ContactPagerActivity.newIntent(this, contact.getIDD());
startActivity(intent);
} else {
Fragment newDetail = ContactFragment.newInstance(contact.getId());
getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_fragment_container, newDetail)
.commit();
}
}
public void onContactUpdated(Contact crime) {
ContactListFragment listFragment = (ContactListFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
listFragment.updateUI();
}
}
could any one show me whre I am doing wrong because I see the followoig error in my log
Process: com.bignerdranch.android.adressbook, PID: 28871
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.bignerdranch.android.adressbook.Contact.getName()' on a null object reference
atcom.bignerdranch.android.adressbook.ContactFragment.onCreateView(ContactFragment.java:82)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)

push data from Fragment to Fragment

I am new to Android. Please excuse me if it's a silly question:
If i click on button of a Fragment - it has to trigger a test and show the result in other Fragment. So to make things simple, have written a code on button click as follows. It's not working. Please suggest.
My actual intent is to register a log.add BroadcastReceiver, so that anywhere any log error or debug is called, that message has to appear in the TestStatusFragment.
public class TriggerTestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trigger, container, false);
Button stopScheduler = (Button) view.findViewById(R.id.testButton);
stopScheduler.setOnClickListener((View sview) -> {
View teststatusView = inflater.inflate(R.layout.fragment_teststatus, container, false);
TextView textView = (TextView) teststatusView.findViewById(R.id.text_view);
textView.setText("test result....");
});
return view;
}
}
MainActivity.java
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TriggerTestFragment(), "TRIGGERTEST");
adapter.addFragment(new TestStatusFragment(), "TEST STATUS");
viewPager.setAdapter(adapter);
}
Second Fragment:
public class TestStatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teststatus, container, false);
return view;
}
}
Use interface to communicate between them.
Fragment One
public class FragOne extends Fragment {
EditText etxtName, etxtDesc;
Button btnSubmit;
String name, desc;
private OnFragmentInteractionListener mListener;
public FragOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_one, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etxtName = (EditText) view.findViewById(R.id.etxtName);
etxtDesc = (EditText) view.findViewById(R.id.etxtDesc);
btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxtName.getText().toString().trim();
desc = etxtDesc.getText().toString().trim();
if(name == null || desc == null) {
Toast.makeText(getActivity(), "Both fields required", Toast.LENGTH_SHORT).show();
} else {
mListener.onFragmentInteraction(name, desc);
etxtName.setText("");
etxtDesc.setText("");
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String name, String desc);
}
}
Fragment Two
public class FragTwo extends Fragment implements FragOne.OnFragmentInteractionListener{
TextView textView, textDesc;
public FragTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_two, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(R.id.txtName);
textDesc = (TextView) view.findViewById(R.id.txtDesc);
}
#Override
public void onFragmentInteraction(String name, String desc) {
textView.setText(name);
textDesc.setText(desc);
}
}
Init fragments
fragOne = new FragOne();
fragTwo = new FragTwo();
PagerAdapter
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
MainActivity need implement onFragmentInteraction interface
public class MainActivity extends AppCompatActivity implements FragOne.OnFragmentInteractionListener{
static FragOne fragOne;
static FragTwo fragTwo;
MyPagerAdapter myPagerAdapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragOne = new FragOne();
fragTwo = new FragTwo();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
#Override
public void onFragmentInteraction(String name, String desc) {
myPagerAdapter.onFragmentInteraction(name, desc );
}
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
}
You can read full article here https://www.mytrendin.com/passing-data-between-fragments/

How to handle back button in tab's fragment?

I have an activity,and have 2 fragments thats name is AddressFragment and ProfileFragment thats extend from BaseFragment.
How i can handle back button in tab fragment.
if a info_ll(a linearlayout) is show,when back button is pressed gone and a recyclerview is show
and if recyclerview is showing,when back press button clicked finish activity
public class ProfileActivity extends AppCompatActivity{
TabLayout tabLayout;
ViewPager viewPager;
public void setTv_name(String tv_name) {
ProfileActivity.tv_name.setText(tv_name);
}
public void setTv_email(String tv_email) {
ProfileActivity.tv_email.setText(tv_email);
}
public void setTv_phone(String tv_phone) {
ProfileActivity.tv_phone.setText(tv_phone);
}
public static MyTextView tv_name;
public static MyTextView tv_email;
public static MyTextView tv_phone;
CircularImageView iv_profile;
ImageButton btn_back;
BaseFragment currentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
TabLayout tabhost = (TabLayout) this.findViewById(R.id.tabs);
tabhost.getTabAt(getIntent().getIntExtra("go_to",0)).select();
tv_name= (MyTextView) findViewById(R.id.tv_name);
tv_email= (MyTextView)findViewById(R.id.tv_email);
tv_phone= (MyTextView)findViewById(R.id.tv_phone);
iv_profile= (CircularImageView) findViewById(R.id.profile);
btn_back= (ImageButton) findViewById(R.id.btn_Back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ProfileFragment(), "ویرایش اطلاعات");
adapter.addFragment(new AddressFragment(), "آدرس های منتخب");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
currentFragment = null;
switch (position) {
case 0:
currentFragment = new ProfileFragment();
break;
case 1:
currentFragment = new AddressFragment();
break;
}
return currentFragment;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setImage(){
if(!DataContainer.getObject().getProfileImagePath().equals("None"))
Glide.with(this).load(DataContainer.getObject().getProfileImagePath()).into(iv_profile);
}
#Override
public void onBackPressed() {
if(currentFragment == null || !currentFragment.onBackPressed())
super.onBackPressed();
}
}
AddressFragment
public class AddressFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
ProgressDialog pDialog;
int pDilog_Counter=0;
private View rootView;
private RecyclerView recyclerView;
MyEditText et_title;
MyEditText et_address;
LinearLayout info_ll;
Button btn_edit;
ImageButton btn_location;
FloatingActionButton fab;
double latitude;
double longitude;
public static final int RESULT_OK = -1;
int status=0;
int profileID=0;
public AddressFragment() {
}
public static AddressFragment newInstance(String param1, String param2) {
AddressFragment fragment = new AddressFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_address, container, false);
info_ll= (LinearLayout) rootView.findViewById(R.id.info_ll);
et_title= (MyEditText) rootView.findViewById(R.id.et_title);
et_address= (MyEditText) rootView.findViewById(R.id.et_address);
btn_edit= (Button) rootView.findViewById(R.id.btn_edit);
btn_location= (ImageButton) rootView.findViewById(R.id.btn_location);
fab= (FloatingActionButton) rootView.findViewById(R.id.fab);
recyclerView= (RecyclerView) rootView.findViewById(R.id.Address_recycler);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setVisibility(View.GONE);
fab.setVisibility(View.GONE);
info_ll.setVisibility(View.VISIBLE);
status=0;
btn_edit.setText("ثبت");
//PAProfileAddressAdd();
}
});
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private JSONArray Addresses;
AddressFragment addressFragment;
public SimpleAdapter(AddressFragment addressFragment, JSONArray AddressArray) {
this.addressFragment=addressFragment;
this.Addresses=AddressArray;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.address_recyclerview_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return Addresses.length();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private MyTextView title;
private int position;
public ViewHolder(View itemView) {
super(itemView);
title = (MyTextView) itemView.findViewById(R.id.address_txt);
itemView.setOnClickListener(this);
}
public void bind(int position) {
this.position = position;
try {
title.setText(Addresses.getJSONObject(position).getString("Title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
addressFragment.status=1;
addressFragment.rootView.findViewById(R.id.Address_recycler).setVisibility(View.GONE);
addressFragment.rootView.findViewById(R.id.fab).setVisibility(View.GONE);
addressFragment.rootView.findViewById(R.id.info_ll).setVisibility(View.VISIBLE);
addressFragment.et_title.setEnabled(false);
addressFragment.et_address.setEnabled(false);
try {
addressFragment.et_title.setText(Addresses.getJSONObject(position).getString("Title"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
addressFragment.et_address.setText(Addresses.getJSONObject(position).getString("Address"));
} catch (JSONException e) {
e.printStackTrace();
}
addressFragment.status=1;
try {
addressFragment.profileID=Integer.parseInt(Addresses.getJSONObject(position).getString("ProfileAddressID"));
} catch (JSONException e) {
e.printStackTrace();
}
//TODO open edit dialog for Addresses.getJSONObject(position)
}
}
}
#Override
public boolean onBackPressed() {
if(info_ll.getVisibility()==View.VISIBLE){
fab.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
info_ll.setVisibility(View.GONE);
return true;
}else {
return false;
}
}
}
ProfileFragment
public class ProfileFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
Button btn_edit;
EditText et_name;
EditText et_phone;
EditText et_email;
ProgressDialog pDialog;
int pDilog_Counter=0;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_profile, container, false);
btn_edit=(Button) v.findViewById(R.id.btn_edit);
et_name= (EditText) v.findViewById(R.id.et_name);
et_email= (EditText) v.findViewById(R.id.et_email);
et_phone= (EditText) v.findViewById(R.id.et_phone);
PAProfileInfo();
btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PAProfileEdit();
}
});
((ProfileActivity)getActivity()).setImage();
return v;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
private void PAProfileInfo() {
String url="http://RO.nirasoftware.com:8888/WS/WSPAProfileInfo.aspx?"+
"CustomerCode="+ DataContainer.getObject().getCustomerCode() +
"&TokenID="+ DataContainer.getObject().getTokenID() +
"&Type=JSON&VS="+DataContainer.getObject().getVersion();
showProgress();
StringRequest request = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject NRS=(new JSONObject(response)).getJSONObject("NRS");
if(NRS.getJSONObject("Error").getInt("ErrCode")==0){
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
try {
et_name.setText(NRS.getJSONObject("Customer").getString("CustomerFullName"));
et_email.setText(NRS.getJSONObject("Customer").getString("EMail"));
et_phone.setText(NRS.getJSONObject("Customer").getString("MobileNo"));
((ProfileActivity)getActivity()).setTv_name(NRS.getJSONObject("Customer").getString("CustomerFullName"));
((ProfileActivity)getActivity()).setTv_email(NRS.getJSONObject("Customer").getString("EMail"));
((ProfileActivity)getActivity()).setTv_phone(NRS.getJSONObject("Customer").getString("MobileNo"));
}catch (JSONException e){
}
hideProgress();
}else{
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
hideProgress();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error in json received", Toast.LENGTH_LONG).show();
hideProgress();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme);
// 2. Chain together various setter methods to set the dialog characteristics
String s=error.getMessage();
if(error.networkResponse==null)
s="سرعت کم اتصال";
else
s+="\nResponse:\n\t"+error.networkResponse.toString();
builder.setMessage(s).setTitle("خطا:");
// 3. Get the AlertDialog from create()
AlertDialog dg = builder.create();
dg.setButton(AlertDialog.BUTTON_POSITIVE, "تلاش مجدد", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ProfileFragment.this.PAProfileInfo();
} });
dg.setButton(AlertDialog.BUTTON_NEGATIVE, "انصراف", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
} });
dg.show();
hideProgress();
//getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
DataContainer.getObject().getRequestQueue().add(request);
}
private void PAProfileEdit() {
String url="http://RO.nirasoftware.com:8888/WS/WSPAProfileEdit.aspx?"+
"CustomerCode="+ DataContainer.getObject().getCustomerCode() +
"&TokenID="+ DataContainer.getObject().getTokenID() +
"&Type=JSON&VS="+DataContainer.getObject().getVersion()+
"&FullName="+et_name.getText().toString()+
"&Email=" + et_email.getText().toString()+
"&Phone="+et_phone.getText().toString();
showProgress();
StringRequest request = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject NRS=(new JSONObject(response)).getJSONObject("NRS");
if(NRS.getJSONObject("Error").getInt("ErrCode")==0){
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
((ProfileActivity)getActivity()).setTv_name(et_name.getText().toString());
DataContainer.getObject().setName(et_name.getText().toString());
((ProfileActivity)getActivity()).setTv_email(et_email.getText().toString());
DataContainer.getObject().setEMail(et_email.getText().toString());
((ProfileActivity)getActivity()).setTv_phone(et_phone.getText().toString());
DataContainer.getObject().setPhoneNo(et_phone.getText().toString());
hideProgress();
}else{
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
hideProgress();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error in json received", Toast.LENGTH_LONG).show();
hideProgress();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme);
// 2. Chain together various setter methods to set the dialog characteristics
String s=error.getMessage();
/* if(error.networkResponse!=null)
//TODO #$# s+="\nResponse:\n\t"+error.networkResponse.toString();
else*/
s="سرعت کم اتصال";
builder.setMessage(s).setTitle("خطا:");
// 3. Get the AlertDialog from create()
AlertDialog dg = builder.create();
dg.setButton(AlertDialog.BUTTON_POSITIVE, "تلاش مجدد", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PAProfileEdit();
} });
dg.show();
hideProgress();
//getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
DataContainer.getObject().getRequestQueue().add(request);
}
private void showProgress() {
pDilog_Counter++;
if(pDilog_Counter>1)
return;
pDialog = new ProgressDialog(getActivity(),R.style.AppCompatAlertDialogStyle);
pDialog.setMessage("لطفا منتظر بمانید....");
pDialog.show();
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
private void hideProgress() {
pDilog_Counter--;
if(pDilog_Counter>0)
return;
pDialog.hide();
pDialog.dismiss();
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
public boolean onBackPressed() {
return false;
}
}
BaseFragment
public abstract class BaseFragment extends Fragment {
public abstract boolean onBackPressed();
}
You have to give each fragment a unique TAG it will help you to easily retrieve
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "First Fragment")
.commit();
Retrieve(e.g. in on back pressed)
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FirstFragment");
if (fragment == null) {
fragment = new PlaceholderFragment();
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment, "FirstFragment")
.commit();
Fainally i found solution I find the current fragment's tag which show in viepager and compare whit AddressFragment class
#Override
public void onBackPressed() {
BaseFragment fragment =
(BaseFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:"+R.id.viewpager+":"+viewPager.getCurrentItem());
if(fragment instanceof AddressFragment) // could be null if not instantiated yet
{
if(!fragment.onBackPressed())
super.onBackPressed();
}else
super.onBackPressed();

Update the row item data of recyclerview

The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.

Categories

Resources