android value passing adapter to fragment - android

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

Related

How to refresh Fragment inside ViewPager

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
}
}

How to pass a variable from adapter to fragment?

I have a recyclerview. Once user clicked on any item of recyclerview item it should open a new fragment. But I would like to pass a id with it like we send with intent using putExtra.
Below is my adapter onBindViewHolder method code -
public void onBindViewHolder(#NonNull DashboardViewHolder holder, int position) {
final Dashboard product = dashboardList.get(position);
//loading the image
Glide.with(mCtx)
.load(product.getImage())
.into(holder.imageView);
holder.rate.setText(product.getRate());
holder.name.setText(product.getName());
holder.city.setText(product.getCity());
//holder.id.setText(String.valueOf(product.getId()));
holder.boatList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mCtx, ""+String.valueOf(product.getId()), Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(mCtx, AddNewBoatFragment.class);
//intent.putExtra("boat_id", product.getId());
//intent.putExtra("owner_id", product.getOwner_id());
//mCtx.startActivity(intent);
//getSupportFragmentManager().beginTransaction().replace(R.id.dahsboard_fragment,
//new MyBoatFragment()).commit();
Fragment fragment = new AddNewBoatFragment();
FragmentManager fm = ((AppCompatActivity)mCtx).getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.dahsboard_fragment, fragment);
ft.commit();
}
});
}
Below is my class -
public Dashboard(int id, int owner_id, String image, String rate, String name, String city){
this.id = id;
this.owner_id = owner_id;
this.image = image;
this.rate = rate;
this.name = name;
this.city = city;
}
public int getId(){ return id; }
public String getImage() {
return image;
}
public String getRate() { return rate; }
public String getName(){
return name;
}
public String getCity() { return city; }
public int getOwner_id() { return owner_id; }
You should declare a static method in AddNewBoatFragment to create a Fragment instance from given params.
public class AddNewBoatFragment extends Fragment {
private static final String ARGUMENT_BOAT_ID = "ARGUMENT_BOAT_ID";
private static final String ARGUMENT_OWNER_ID = "ARGUMENT_OWNER_ID";
public static AddNewBoatFragment newInstance(int boatId, String ownerId) {
Bundle args = new Bundle();
// Save data here
args.putInt(ARGUMENT_BOAT_ID, boatId);
args.putString(ARGUMENT_OWNER_ID, ownerId);
AddNewBoatFragment fragment = new AddNewBoatFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
// Retrieve the data here
int boatId = getArguments().getInt(ARGUMENT_BOAT_ID);
String ownerId = getArguments().getString(ARGUMENT_OWNER_ID);
return view;
}
}
And modify block code in onClick method from the Adapter class.
holder.boatList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = AddNewBoatFragment.newInstance(product.getId(), product.getOwner_id());
FragmentManager fm = ((AppCompatActivity)mCtx).getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.dahsboard_fragment, fragment);
ft.commit();
}
});
You can send using Bundle
Fragment fragment = new AddNewBoatFragment();
Bundle bundle = new Bundle();
bundle.putString("myIDKey",product.getId());
fragment.setArguments(bundle);
FragmentManager fm = ((AppCompatActivity)mCtx).getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.dahsboard_fragment, fragment);
ft.commit();
and in OnCreateView method of Fragment you can get attached arguments and use it
I just put those variables which need to pass to a fragment as Public Static
which can be accessed from any other class

How to open fragment from adapter class without using Intent?

I want to call Fragment from Adapter Class but not able to do so..
So please some method to call the fragment. I have got a method of first calling activity and then switching the fragment is there any other method
Here is the code:
public class FanAdapter extends RecyclerView.Adapter<FanAdapter.MyViewHolder>
{
private Context mContext;
private List<Fan> FanList;
public class MyViewHolder extends RecyclerView.ViewHolder
{
public TextView testTitle;
public CardView mCardView;
public MyViewHolder(View view)
{
super(view);
mCardView = (CardView) view.findViewById(R.id.card_view);
testTitle = (TextView) view.findViewById(R.id.fan_name);
}
}
public FanAdapter(Context mContext, List<Fan> FanList)
{
this.mContext = mContext;
this.FanList = FanList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fanslist, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Fan album = FanList.get(position);
holder.testTitle.setText(album.getName());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Slecteditem= String.valueOf(position);
Bitmap bmp = BitmapFactory.decodeResource(Resources.getSystem(), position);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Fragment fragment = new ProfileDisplay();
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Bundle args = new Bundle();
args.putString("itemname", Slecteditem);
args.putByteArray("picture", byteArray);
fragment.setArguments(args);
fragmentTransaction.replace(R.id.fl_toplayout, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Toast.makeText(mContext,"Profile"+album.getName(),Toast.LENGTH_LONG).show();
}
});
// loading album cover using Glide library
}
#Override
public int getItemCount()
{
return FanList.size();
}
}
The editor is not able to resolve getActivity() method in
FragmentManager fm = getActivity().getFragmentManager();
Pass the mContext to getFragmentManager();. Cast the mContext to Activity.
Something like this.
FragmentManager fm = (Activity)mContext.getFragmentManager();
The better way to do so would be using a interface to notify the class which calls the adapter.
Something like this:
public interface NotifyChange {
void onItemClicked();
}
Then in onItemClicked() do the operation, you want to achieve.
Considering your question, if you a calling the FanAdapter class in a fragment, create a FragmentManager inside FanClass List like this
private FragmentManager fragment;
public FragmentManager getFragment() {
return fragment;
}
public void setFragment(FragmentManager fragment) {
this.fragment = fragment;
}
and also add it to the Fan constructor
public Fan(FragmentManager fm){
this.fragment=fm;
}
In your OnClickListener body
FragmentTransaction ft=fan.get(position).getFragment().beginTransaction();
ft.replace(R.id.nav_host_fragment,fd);
ft.commit();
In Your List you should add getFragmentManager();
fan.add(new fan(your,own,variables,getFragmentManager()));
Use this code for replacing fragment from adapter class;
Fragment fragment = new YourFragmentName();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Bundle args = new Bundle();
args.putString("itemname", Slecteditem);
args.putByteArray("picture", byteArray);
fragment.setArguments(args);

Display value on listitem of listview from Arraylist

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.

Android restore from backstack give me blank fragment

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

Categories

Resources