Two fragments,
first fragment sends arraylist of product name and price to second fragment,
Second fragment gets all values properly
Question
I want to display data on TextView. How can it possible?
Below is my code
First Fragment
alists=new ArrayList<String>();
System.out.println("ARRAYLIST><><><><><"+alists);
GenericUtility.setStringToSharedPrefsForKey("selected_prodname", user_name, getActivity());
GenericUtility.setStringToSharedPrefsForKey("selected_prodprc", dollars+prod_price, getActivity());
btn_add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cartincrement();
productnams = GenericUtility.getStringFromSharedPrefsForKey("selected_prodname", getActivity());
System.out.println("Seleced user name=-=-=-=-=-=-==-=" + productnams);
productprc = GenericUtility.getStringFromSharedPrefsForKey("selected_prodprc", getActivity());
System.out.println("Seleced prodprice=-=-=-=-=-=-==-=" + productprc);
alists.add(productnams);
alists.add(productprc);
}
});
relcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Add_to_cart tf = new Add_to_cart();
Bundle bundle = new Bundle();
bundle.putStringArrayList("prodnam", alists);
// bundle.putString("prodprce", productprc);
tf.setArguments(bundle);
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
}
Second Fragment
public class Add_to_cart extends Fragment {
private Button continue_shopping;
private Button checkout;
ListView list;
private TextView _decrease,mBTIncrement,_value;
private CustomListAdapter adapter;
private ArrayList<String> alst;
private String bname;
public Add_to_cart(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false);
alst=new ArrayList<String>();
Bundle bundle = this.getArguments();
alst = bundle.getStringArrayList("prodnam");
System.out.println("NAM--"+alst);
/* for(int i=0;i<alst.size();i++)
{
bname=alst.get(i);
}*/
continue_shopping=(Button)rootView.findViewById(R.id.btn_continueshoppping);
checkout=(Button)rootView.findViewById(R.id.btn_chckout);
adapter = new CustomListAdapter(getActivity(),alst);
list=(ListView)rootView.findViewById(R.id.list_addtocart);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
continue_shopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HomeFragment tf = new HomeFragment();
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Checkout tf = new Checkout();
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
public class CustomListAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> listData;
//private AQuery aQuery;
String dollars="\u0024";
public CustomListAdapter(Context context,ArrayList<String> listData) {
this.context = context;
this.listData=listData;
// aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.txtproname = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.proprice_addtocart);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position));
holder.txtprofilecast.setText(dollars+listData.get(position));
//holder.txtprofilecast.setText(dollars+listData.get(position));
// aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtprofilecast;
}
Your problem is that your list of items is actually twice as long as it should be. If you have 4 items in your list you will have 8 entries in your array (each item has 2 entries, a name and a price).
Instead of adding the name and price to a single array, you should create 2 parallel arrays. The first containing the list of names and the second containing the list of prices. Pass both arrays to the second fragment.
Related
I have searched a lot but can't find solution which will be suitable for my code.
Actually i have tablayout in fragment and for tablayout i am using viewpager. There are 3 fragments inside viewpager. There is one spinner in my activity i want when user selects item from spinner then viewpager fragments data should be changed according to selected value but it is not updating the data.
Can anyone help to solve it. I want viewpager fragment should be refreshed whenever spinner's selected value will be changed.
My MainActivity code:
binding.bottmNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.location:
final AlertDialog.Builder mbuilder = new AlertDialog.Builder(HomeActivity.this);
View v = getLayoutInflater().inflate(R.layout.dialog_layout, null);
Button okbutton = v.findViewById(R.id.okbutton);
final Spinner spinner = (Spinner) v.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.countries_list));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
mbuilder.setView(v);
final AlertDialog dialog = mbuilder.create();
okbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Dialog123", "onClick: Positive" );
SharedPreferences prfs;
prfs = PreferenceManager.getDefaultSharedPreferences(HomeActivity.this);
SharedPreferences.Editor editor = prfs.edit();
editor.putString("savedvalue", spinner.getSelectedItem().toString());
editor.commit();
String text = spinner.getSelectedItem().toString();
newsModels = new ArrayList<>();
if(text.equals("INDIA")) {
newsModels.clear();
TypedArray indianewslogo = getResources().obtainTypedArray(R.array.indianews);
String[] indianewsname = getResources().getStringArray(R.array.indianewsnames);
String[] indianewsurl = getResources().getStringArray(R.array.indiahref);
for(int i =0; i<indianewslogo.length(); i++) {
//SendModel sendModel = new SendModel(indianewslogo.getResourceId(i,0),indianewsname[i]);
newsModels.add(new NewsModel(indianewslogo.getResourceId(i,0),indianewsname[i], indianewsurl[i]));
}
Singleton.getConstant().addNewsModel(newsModels);
TypedArray indiashopimg = getResources().obtainTypedArray(R.array.indiashopimg);
String [] indishopname = getResources().getStringArray(R.array.indiashopname);
String[] indiashopurl = getResources().getStringArray(R.array.indiashopurl);
sendModels = new ArrayList<>();
for(int j =0; j<indiashopimg.length(); j++){
SendModel sendModel = new SendModel(indiashopimg.getResourceId(j,0), indishopname[j], indiashopurl[j]);
sendModels.add(sendModel);
}
SendSingleton.getConstant().addNewsModel(sendModels);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, homeFragment);
fragmentTransaction.commit();
binding.bottmNav.getMenu().findItem(R.id.location).setTitle("India");
binding.bottmNav.getMenu().findItem(R.id.home1).setChecked(true);
dialog.dismiss();
}else if(text.equals("USA")){
newsModels.clear();
TypedArray indianewslogo = getResources().obtainTypedArray(R.array.usnews);
String[] indianewsname = getResources().getStringArray(R.array.usnewsname);
String[] indianewsurl = getResources().getStringArray(R.array.usurl);
for(int i =0; i<indianewslogo.length(); i++) {
newsModels.add(new NewsModel(indianewslogo.getResourceId(i,0),indianewsname[i], indianewsurl[i]));
}
Singleton.getConstant().addNewsModel(newsModels);
Singleton.getConstant().addNewsModel(newsModels);
TypedArray indiashopimg = getResources().obtainTypedArray(R.array.usashopimg);
String [] indishopname = getResources().getStringArray(R.array.usashopname);
String[] indiashopurl = getResources().getStringArray(R.array.usashopurl);
sendModels = new ArrayList<>();
for(int j =0; j<indiashopimg.length(); j++){
SendModel sendModel = new SendModel(indiashopimg.getResourceId(j,0), indishopname[j], indiashopurl[j]);
sendModels.add(sendModel);
}
SendSingleton.getConstant().addNewsModel(sendModels);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, homeFragment);
fragmentTransaction.commit();
binding.bottmNav.getMenu().findItem(R.id.location).setTitle("USA");
binding.bottmNav.getMenu().findItem(R.id.home1).setChecked(true);
dialog.dismiss();
}
HomeFragment(Where viewpager is placed):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final FragmentHomeBinding homeBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
sendModels = new ArrayList<>();
PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), homeBinding.tablayout.getTabCount());
homeBinding.viewpager1.setAdapter(pagerAdapter);
homeBinding.tablayout.setupWithViewPager(homeBinding.viewpager1);
homeBinding.viewpager1.getAdapter().notifyDataSetChanged();
homeBinding.tablayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
homeBinding.viewpager1.setCurrentItem(tab.getPosition());
}#Override
public void onTabUnselected(TabLayout.Tab tab) {
}#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
homeBinding.viewpager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(homeBinding.tablayout));
NewsFragment(Where i want to show the data):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final FragmentNewsBinding binding= DataBindingUtil.inflate(inflater, R.layout.fragment_news, container, false);
View view = binding.getRoot();
newsModels = new ArrayList<>();
newsModels =Singleton.getConstant().getNewsModel();
GridLayoutManager gridLayoutManager =new GridLayoutManager(getContext(), 4);
binding.recylerview.setLayoutManager(gridLayoutManager);
binding.recylerview.setItemAnimator(new DefaultItemAnimator());
RecyclerAdapter adapter = new RecyclerAdapter(newsModels, getContext());
binding.recylerview.setAdapter(adapter);
return view;
}
ViewPagerAdapter Code:
public class PagerAdapter extends FragmentPagerAdapter {
private Map<Integer, String> mfragmenttags;
private FragmentManager mfragmentManager;
private String[] tabtitles= new String[]{"News", "Shopping", "Social"};
private int numofTabs;
public PagerAdapter(#NonNull FragmentManager fm, int numofTabs) {
super(fm);
mfragmentManager = fm;
this.numofTabs = numofTabs;
mfragmenttags = new HashMap<Integer, String>();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new NewsFragment();
case 1:
return new ShoppingFragment();
case 2:
return new SocialFragment();
default:
return null;
}
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if(obj instanceof Fragment ){
Fragment f = (Fragment)obj;
String tag = f.getTag();
mfragmenttags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position){
String tag = mfragmenttags.get(position);
if(tag == null){
return null;
}
return mfragmentManager.findFragmentByTag(tag);
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return numofTabs;
}
}
You should put all logic code fetch data (or load data) in both place are onCreated and onNewIntent
onCreated is called in first time
onNewIntent is called when u show again that fragment
Hope this help!
Create public methods refresh() inside your fragments that you want to refresh. Add the below code to call refresh() inside your setOnItemSelectedListener of the spinner
for (Fragment fragment : getChildFragmentManager().getFragments()) {
if (fragment instanceof NewsFragment) {
((NewsFragment) fragment).refresh(); //add refresh method in fragment
}
}
Hi I am using Tablayout in my
TAB1 TAB2 TAB3
When I open the app, by default TAB1 is selected. All the TABs have recyclerview. Now I have one FAB button for all the fragments. I am using FAB button for changing language.
Whenever user change language data will display as per language selection. Now issue is When I am on TAB3 and changing language instead of staying on TAB3 it goes to TAB1.
Can any one help me to solve this issue.
public class LibraryFragment extends Fragment {
private static final String TAG = LibraryFragment.class.getSimpleName();
private TabLayout tabLayout;
private ViewPager viewPager;
private String catid;
private FragmentManager fragmentManager;
private String SELECTED_ACTION;
private String SELECTED_LANGUAGE,SELECTED_LANGUAGENM,sel_cat;
private int VID_CODE;
private FloatingActionButton fab;
private ArrayList<LanguageModel> langList;
public LibraryFragment() {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library, container, false);
langList = (ArrayList<LanguageModel>) getArguments().getSerializable("langlist");
catid = getArguments().getString("frommusic");
SELECTED_ACTION = getArguments().getString("action");
SELECTED_LANGUAGE = getArguments().getString("sel_lang");
SELECTED_LANGUAGENM = getArguments().getString("sel_langnm");
sel_cat = getArguments().getString("sel_cat");
System.out.println("in library" + SELECTED_LANGUAGE);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager = (ViewPager) view.findViewById(R.id.view_pager);
viewPager.setAdapter(new CustomFragmentPageAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
fab = (FloatingActionButton) view.findViewById(R.id.fabChat);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setdailog();
}
});
return view;
}
public void setdailog()
{
final Dialog cpDialog = new Dialog(getActivity());
cpDialog.setTitle("Select Language");
cpDialog.setContentView(R.layout.alert_list);
ListView listView = (ListView) cpDialog.findViewById(R.id.listiview_lang);
AlertListAdapter mAdapter = new AlertListAdapter(langList, getActivity());
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SELECTED_LANGUAGE = langList.get(position).getLangid();
System.out.println("JO JO"+SELECTED_LANGUAGE);
Intent intent=new Intent(getActivity(),MusicActivity.class);
intent.putExtra("langlist",langList);
intent.putExtra("selid",catid);
intent.putExtra("langid",SELECTED_LANGUAGE);
intent.putExtra("langname",langList.get(position).getLangname());
intent.putExtra("selcat",sel_cat);
startActivity(intent);
cpDialog.dismiss();
}
});
cpDialog.show();
}
public class AlertListAdapter extends BaseAdapter {
ArrayList<LanguageModel> mData;
Context mContext;
LayoutInflater inflater;
public AlertListAdapter(ArrayList<LanguageModel> data, Context context) {
mData = data;
mContext = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_alert_list, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.textView_languge);
tvTitle.setText(mData.get(position).getLangname());
return convertView;
}
}
public class CustomFragmentPageAdapter extends FragmentPagerAdapter {
private final String TAG = CustomFragmentPageAdapter.class.getSimpleName();
private static final int FRAGMENT_COUNT = 3;
public CustomFragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment f1 = new SongFragment();
Bundle args1 = new Bundle();
args1.putString("fromlibfrag", catid);
args1.putString("action", SELECTED_ACTION);
args1.putString("sel_lang", SELECTED_LANGUAGE);
args1.putSerializable("langlist",langList);
f1.setArguments(args1);
return f1;
case 1:
Fragment f2 = new PhotoFragment();
Bundle args2 = new Bundle();
args2.putString("fromlibfrag", catid);
args2.putString("action", SELECTED_ACTION);
args2.putString("sel_lang", SELECTED_LANGUAGE);
args2.putSerializable("langlist",langList);
f2.setArguments(args2);
return f2;
case 2:
Fragment f3 = new SmsFragment();
Bundle args3 = new Bundle();
args3.putString("fromlibfrag", catid);
args3.putString("action", SELECTED_ACTION);
args3.putString("sel_lang", SELECTED_LANGUAGE);
args3.putSerializable("langlist",langList);
f3.setArguments(args3);
return f3;
}
return null;
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Videos";
case 1:
return "Photos";
case 2:
return "SMS";
}
return null;
}
}
}
int position=0;
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override public void onTabSelected(TabLayout.Tab tab){
position = tab.getPosition();
} });
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setdailog(position);
}
});
Now
public void setdailog(int currentTab)
{
final Dialog cpDialog = new Dialog(getActivity());
cpDialog.setTitle("Select Language");
cpDialog.setContentView(R.layout.alert_list);
ListView listView = (ListView) cpDialog.findViewById(R.id.listiview_lang);
AlertListAdapter mAdapter = new AlertListAdapter(langList, getActivity());
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SELECTED_LANGUAGE = langList.get(position).getLangid();
System.out.println("JO JO"+SELECTED_LANGUAGE);
Intent intent=new Intent(getActivity(),MusicActivity.class);
intent.putExtra("langlist",langList);
intent.putExtra("selid",catid);
intent.putExtra("langid",SELECTED_LANGUAGE);
intent.putExtra("langname",langList.get(position).getLangname());
intent.putExtra("selcat",sel_cat);
intent.putExtra("currentTab" , currentTab);
startActivity(intent);
finish();
cpDialog.dismiss();
}
});
cpDialog.show();
}
Now In MusicActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int currentTab = intent.getIntExtra("currenttab", 0);
//here you can check if you get 1, 2 or 3 in currentTab then you have to set current tab to 1, 2 or 3 respectively.
}
I am developing an app for displaying images and text. When clicking on the item it goes to another fragment. The listing showing is correct but when I click on the item it does not go to fragment. I am using recycler adapter to listing the items. The code is shown below.
public class MyRecyclerAdapter extends RecyclerView.Adapter < MyRecyclerAdapter.MyViewHolder > {
String categoryId;
private List < NewsFeeds > feedsList;
private Context context;
private LayoutInflater inflater;
public MyRecyclerAdapter(Context context, List < NewsFeeds > feedsList) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.singleitem_recyclerview_categories, parent, false);
return new MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NewsFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
holder.title.setText(feeds.getName());
//holder.categoryId.setText(feeds.getCategory_id());
categoryId = feeds.getCategory_id();
Log.d("LOGTAG", "id : " + categoryId);
holder.imageview.setImageUrl(feeds.getImgURL(), NetworkController.getInstance(context).getImageLoader());
Log.d("LOGTAG", "feeds.getFeedName():" + feeds.getName());
}
#Override
public int getItemCount() {
return feedsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private NetworkImageView imageview;
private CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_view);
//categoryId = (TextView) itemView.findViewById(R.id.content_view);
// Volley's NetworkImageView which will load Image from URL
imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
Log.d("LOGTAG", categoryId);
Log.d("LOGTAG", "clicked");
//newInstance(categoryId);
}
});
}
}
}
I want to send value to SubCategoryFragment and start SubCategoryFragment.
my SubCategoryFragment code
public class SubCategoryFragment extends Fragment {
public SubCategoryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sub_category, container, false);
//Bundle bundle = this.getArguments();
Bundle args = getArguments();
//String categoryId = args.getString("index");
String categoryId = getArguments().getString("category_id");
//String categoryId = getArguments().getString("category_id");
TextView textView = (TextView) rootView.findViewById(R.id.label);
textView.setText(categoryId);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Please help me
From Adapter you send data with intent as:
Fragment fragment = new tasks();
FragmentManager fragmentManager = context.getSupportFragmentManager(); // this is basically context of the class
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("name", "From Adapter"); //key and value
//set Fragmentclass Arguments
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
String strtext=getArguments().getString("name"); //fetching value by key
return inflater.inflate(R.layout.fragment, container, false);
}
In your onClickListener();
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Change R.id.content_frame with your fragment
You have made one mistake in your onClick method.
When you want to go one fragment to other fragment, you have to transaction the fragment using FragmentTransaction.class
Check out below code.
Edit :
SecondFragment fragment = new SecondFragment();
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.hide(currentfragment) fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
Edit :
Just put below code in your RecyclerViewAdapter method onBindViewHolder.
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragobj);
fragmentTransaction.hide(currentfragment);
fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
EDIT :
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
String categoryId;
private List<NewsFeeds> feedsList;
private Context context;
private LayoutInflater inflater;
private Fragment currentFragment;
public MyRecyclerAdapter(Context context, List<NewsFeeds> feedsList, final Fragment currentFragment) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.currentFragment = currentFragment;
}
#Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.singleitem_recyclerview_categories, parent, false);
return new MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NewsFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
holder.title.setText(feeds.getName());
//holder.categoryId.setText(feeds.getCategory_id());
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragobj);
fragmentTransaction.hide(currentfragment);
fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
}
#Override
public int getItemCount() {
return feedsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_view);
}
}
}
Replace your onclick listener with this.
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
Log.d("LOGTAG", categoryId);
Log.d("LOGTAG", "clicked");
//put this in your code
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.SubCategoryFragment, fragobj);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
My ViewPager is not working correctly. I don't know what's wrong with my code. I am facing some problems with my Fragments:
Basically, I have a Fragment named MyListFragment that has a list and on the click event of list item I move to the second Fragment named FlowersFragment that has a ViewPager with three items(Another three Fragments) in it. And i have a Button in my FlowersFragment and on click of that Button i move to the third screen named WelcomeFragment. now i have a problem :
If i go back to FlowersFragment from WelcomeFragment then it loses some Fragments from ViewPager after some research i got a solution like use childFragmentManager while creating adapter. That is good for my pager all Fragments are now showing correctly in my FlowersFragment Pager. But if I go back to MyListFragment and I click on second or third item of ListFragment its showing me exception with NO ACTIVITY.
Here is my FirstFragment named MyListFragment
public class MyListFragment extends Fragment{
private View view;
private FragmentManager fm;
private FragmentTransaction ft;
private ListView listviewPlaces;
private FloristAdapter adapter;
private ArrayList<FloristItems> items = new ArrayList<FloristItems>();
private FlowersFragment frag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = LayoutInflater.from(getActivity());
view = inflater.inflate(R.layout.fragment_list, container,false);
listviewPlaces = (ListView)view.findViewById(R.id.listviewPlaces);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
for (int i = 0; i < 10; i++) {
FloristItems florist = new FloristItems();
florist.away = "3 miles away";
florist.title = "Florist Flowers";
florist.price = "$45";
items.add(florist);
}
adapter = new FloristAdapter(getActivity().getApplicationContext(), items);
listviewPlaces.setAdapter(adapter);
listviewPlaces.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(frag == null){
frag = new FlowersFragment();
}
handleFragments(frag);
}
});
}
private void handleFragments(Fragment fragment){
fm = getActivity().getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
}
}
Here is my FlowersFragment class that have view pager with containing three fragments:
public class FlowersFragment extends Fragment{
private View view;
private FragmentManager fm;
private FragmentTransaction ft;
private ViewPager pager;
private Button btnSendThatFlower;
private FlowerPagerAdapter pageAdapter;
private WelcomeFragment welcomeFrag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = LayoutInflater.from(getActivity());
view = inflater.inflate(R.layout.fragment_choose_flower_buyer, container,false);
pager = (ViewPager)view.findViewById(R.id.viewpager);
btnSendThatFlower = (Button)view.findViewById(R.id.btnSendThatFlower);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pageAdapter = new FlowerPagerAdapter(getActivity().getSupportFragmentManager());
pager.setAdapter(pageAdapter);
btnSendThatFlower.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(welcomeFrag == null){
welcomeFrag = new WelcomeFragment();
}
handleFragments(welcomeFrag);
}
});
}
private void handleFragments(Fragment fragment){
fm = getActivity().getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
} }
Here is my pager Adapter class:
public class FlowerPagerAdapter extends FragmentPagerAdapter{
private ArrayList<Fragment> pagerItems;
public FlowerPagerAdapter(FragmentManager fm) {
super(fm);
pagerItems = new ArrayList<Fragment>();
pagerItems.add(FlowerImage1.getInstance());
pagerItems.add(FlowerImage2.getInstance());
pagerItems.add(CustomFlowerFragment.getInstance());
}
#Override
public Fragment getItem(int num) {
if (num == 0) {
return new FlowerImage1();
}
else if(num == 1) {
return new FlowerImage2();
}
else{
return new CustomFlowerFragment.getInstance();
}
}
#Override
public int getCount() {
return pagerItems.size();
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
//super.restoreState(state, loader);
}}
FlowerImage1 FlowerImage1 CustomFlowerFragment are fragments with only imageview.
This is my last fragment WelcomeFragment
public class WelcomeFragment extends Fragment{
private View view;
private FragmentManager fm;
private FragmentTransaction ft;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = LayoutInflater.from(getActivity());
view = inflater.inflate(R.layout.fragment_write_note_buyer, container,false);
return view;
}}
when i am pressing back press then its not showing fragments in viewpager but after swipe on view pager its showing only first or sometimes last pager fragment.
I have also faced same issue ended up adding following code inside fragment adapter.
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
//super.restoreState(state, loader);
}
I was also faced with the same problem, but i fixed it by extending "FragmentStatePagerAdapter" instead of FragmentPagerAdapter. for your case,it would be:
public class FlowerPagerAdapter extends FragmentStatePagerAdapter{
private ArrayList<Fragment> pagerItems;
public FlowerPagerAdapter(FragmentManager fm) {
super(fm);
pagerItems = new ArrayList<Fragment>();
pagerItems.add(FlowerImage1.getInstance());
pagerItems.add(FlowerImage2.getInstance());
pagerItems.add(CustomFlowerFragment.getInstance());
}
#Override
public Fragment getItem(int num) {
if (num == 0) {
return new FlowerImage1();
}
else if(num == 1) {
return new FlowerImage2();
}
else{
return new CustomFlowerFragment.getInstance();
}
}
#Override
public int getCount() {
return pagerItems.size();
}
}
Hi I have problem with backstack. Here is the list of my fragments:
A - Dashboard Fragment
B - NewOrders Fragment
C - Product Fragment
Backstack is working when I navigate A -> B (back pressed) -> A - this is OK
But in this situation A -> B -> C (back pressed) -> B (blank fragment) (back pressed) -> A (blank fragment)
Dashboard Fragment:
public class DashboardFragment extends Fragment implements View.OnClickListener{
public static final String TAG = DashboardFragment.class.getSimpleName();
ImageButton scan;
ImageButton paragon;
ImageButton cart;
ImageButton orders;
public DashboardFragment() { }
public static DashboardFragment newInstance(){
return new DashboardFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Fragment active: ************************************************************");
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
scan = (ImageButton) rootView.findViewById(R.id.scanButton);
paragon = (ImageButton) rootView.findViewById(R.id.paragonButton);
cart = (ImageButton) rootView.findViewById(R.id.cartButton);
orders = (ImageButton) rootView.findViewById(R.id.newOrdersButton);
scan.setOnClickListener(this);
paragon.setOnClickListener(this);
cart.setOnClickListener(this);
orders.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
switch(v.getId()){
case R.id.paragonButton:
ft.replace(R.id.container, ReceiptFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
case R.id.scanButton:
ft.replace(R.id.container, ProductsFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
case R.id.cartButton:
ft.replace(R.id.container, CartFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
case R.id.newOrdersButton:
ft.replace(R.id.container, NewOrdersFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
default:
return;
}
ft.addToBackStack(null);
ft.commit();
}
}
NewOrdersFragment:
public class NewOrdersFragment extends Fragment implements ExpandableListView.OnChildClickListener{
private static final String TAG = NewOrdersFragment.class.getSimpleName();
List<JsonNewOrder> newOrderList;
ExpandableListView listView;
public NewOrdersFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Fragment active: ************************************************************");
View rootView = inflater.inflate(R.layout.fragment_new_orders, container, false);
newOrderList = new ArrayList<>();
listView = (ExpandableListView) rootView.findViewById(R.id.expandableListView);
listView.setOnChildClickListener(this);
listView.setAdapter(new ExpandableListAdapter(getActivity(), newOrderList));
return rootView;
}
public static Fragment newInstance() {
return new NewOrdersFragment();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Long productId = ((JsonOrder)parent.getExpandableListAdapter().getChild(groupPosition, childPosition)).getBarcode();
ProductFragment fragment = ProductFragment.newInstance(String.valueOf(productId));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
return true;
}
#Override
public void onResume() {
super.onResume();
if(NetworkHelper.isConnected(getActivity())) new JSONTask().execute();
}
private class JSONTask extends AsyncTask<Void, Void, String>{
....
}
}
ProductFragment:
public class ProductFragment extends Fragment {
private static final String ARG_EAN = "ean";
private static final String TAG = ProductFragment.class.getSimpleName();
ImageView thumbnail;
private String ean;
public static ProductFragment newInstance(String ean) {
ProductFragment fragment = new ProductFragment();
Bundle args = new Bundle();
args.putString(ARG_EAN, ean);
fragment.setArguments(args);
return fragment;
}
public ProductFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
ean = getArguments().getString(ARG_EAN);
}
}
private void setImage(Bitmap image){
thumbnail.setImageBitmap(image);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Fragment active: ************************************************************");
View rootView = inflater.inflate(R.layout.fragment_product, container, false);
thumbnail = (ImageView) rootView.findViewById(R.id.thumbnail);
TextView gender = (TextView) rootView.findViewById(R.id.gender_text);
TextView category = (TextView) rootView.findViewById(R.id.category_text);
TextView name = (TextView) rootView.findViewById(R.id.name_text);
TextView size = (TextView) rootView.findViewById(R.id.size_text);
TextView color = (TextView) rootView.findViewById(R.id.color_text);
ImageView color_thumb = (ImageView) rootView.findViewById(R.id.color_thumbnail);
TextView price = (TextView) rootView.findViewById(R.id.price_text);
String [] projection = Product.getProjection();
String selection = Product.C_ID + "=?";
String [] selectionArgs = {ean};
Cursor cursor = getActivity().getContentResolver().query(Uri.parse(Product.CONTENT_URI + "/" + ean), projection, selection, selectionArgs, null);
if(cursor.moveToFirst()) {
if (!cursor.isNull(cursor.getColumnIndex(Product.C_GENDER_NAME)))
gender.setText(cursor.getString(cursor.getColumnIndex(Product.C_GENDER_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_CATEGORY_NAME)))
category.setText(cursor.getString(cursor.getColumnIndex(Product.C_CATEGORY_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_PRODUCT_NAME)))
name.setText(cursor.getString(cursor.getColumnIndex(Product.C_PRODUCT_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_PRICE)))
price.setText(cursor.getString(cursor.getColumnIndex(Product.C_PRICE)) + " PLN");
if (!cursor.isNull(cursor.getColumnIndex(Product.C_COLOR_NAME)))
color.setText(cursor.getString(cursor.getColumnIndex(Product.C_COLOR_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_COLOR_HEX)))
color_thumb.setBackgroundColor(Color.parseColor(cursor.getString(cursor.getColumnIndex(Product.C_COLOR_HEX))));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_SIZE_NAME)))
size.setText(cursor.getString(cursor.getColumnIndex(Product.C_SIZE_NAME)));
String [] stockProjection = {Stock.T_NAME + "." + Stock.C_ID, Stock.T_NAME + "." + Stock.C_NAME, ProductsStocks.T_NAME + "." + ProductsStocks.C_AMOUNT};
Cursor stockCursor= getActivity().getContentResolver().query(Uri.parse(ProductsStocks.CONTENT_URI + "/" + cursor.getString(0)), stockProjection, null, null, null);
if(cursor.moveToFirst()){
ListView listView = (ListView) rootView.findViewById(R.id.stock_list);
String [] from = {Stock.C_NAME, ProductsStocks.C_AMOUNT};
int[] to = {R.id.row_stock_name, R.id.row_stock_qty};
listView.setAdapter(new SimpleCursorAdapter(getActivity(), R.layout.row_stock_item, stockCursor, from, to));
}
//stockCursor.close();
if(NetworkHelper.isConnected(getActivity())) new DownloadImage().execute(cursor.getString(cursor.getColumnIndex(Product.C_THUMB_URI)));
}else{
getFragmentManager().beginTransaction().replace(R.id.productContainer, new NoProductFragment()).commit();
}
cursor.close();
return rootView;
}
I'm assuming that you are already handling the onBackPressed() properly and using the popBackStack() method to jump back to the previous fragment.
A fragment should never replace itself. You will always run into problems. Instead, tell the activity that you want to be replaced by another fragment. Something like this:
interface AppEventListener{
void onNewOrdersSelected();
void onDashboardSelected();
}
class MainActivity extends Activity implements AppEventListener{
...
void onNewOrdersSelected(){
//replace fragment with NewOrders fragment
}
void onDashBoardSelected(){
//replace fragment with Dashboard fragment
}
...
#Override
public void onBackPressed() {
FragmentManager manager = getFragmentManager();
int count = manager.getBackStackEntryCount();
if(count==0) {
super.onBackPressed();
}else{
manager.popBackStack();
}
}
}
class DashBoardFragment extends Fragment{
...
public void OnClick(View view){
AppEventListener listener = (AppEventListener) getActivity();
...
case(R.id.NewOrdersButton):
listener.onNewOrdersSelected();
...
}
}