How to pass a variable from adapter to fragment? - android

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

Related

Not able to Update fragments text while swaping cards

I am working on a card swipe and card flip functionality and I am using ViewPager and fragments.
My problem is I am not able to update TextView inside fragments as I swipe the card from left to right or right to left but when I flip the card it update the UI.
I tried everything which is available over Internet but none of the soltuion is working for me.
I am following this link https://github.com/jamesmccann/android-view-pager-cards
Here is my code
public class CardContainerFragment extends Fragment {
private boolean cardFlipped = false;
static TextView textview;
public CardContainerFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_container, container, false);
LinearLayout ll = (LinearLayout)rootView.findViewById(R.id.layout);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
}
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int page = CardActivity.mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = page_index + " of " + card_activity.deck_map.size();
CardActivity.tv.setText(current_page);
super.handleMessage(msg);
}
};
public void flipCard() {
Fragment newFragment = null;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
if (cardFlipped) {
newFragment = new CardFrontFragment();
} else {
newFragment = new CardBackFragment();
}
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
cardFlipped = !cardFlipped;
}
public static class CardFrontFragment extends Fragment {
public CardFrontFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card, container, false);
textview = (TextView)rootView.findViewById(R.id.card_front);
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
String complete_text = card_front_string +" \n \n + \n Tap now to flip this card.";
textview.setText(complete_text);
return rootView;
}
}
public static class CardBackFragment extends Fragment {
public CardBackFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_back, container, false);
TextView textview = (TextView)rootView.findViewById(R.id.card_back);
textview.setMovementMethod(new ScrollingMovementMethod());
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
String deck_data = card_activity.deck_map.get(card_front_string);
textview.setText(deck_data);
return rootView;
}
}
Here is my adapter code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.card_example);
tv = (TextView)findViewById(R.id.tv_card_number);
tv1 = (TextView)findViewById(R.id.tv_card_index);
FragmentManager m = getFragmentManager();
CardPagerAdapter adapter = new CardPagerAdapter(m);
index = getIntent().getStringExtra("index");
card_activity.cardCounter = Integer.parseInt(index);
int count = card_activity.cardCounter;
int final_count = count+1;
String current_page = final_count+" of "+card_activity.deck_map.size();
//CardActivity.tv.setText(current_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
// mViewPager.setAllowedSwipeDirection(CustomViewPager.SwipeDirection.all);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(card_activity.cardCounter);
//mViewPager.setOffscreenPageLimit(1);
//mViewPager.setOnPageChangeListener(new pagechangelistener())
//Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
}catch(Exception e){
e.printStackTrace();
}
}
public class CardPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
mViewPager.setOffscreenPageLimit(0);
int page = mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = " of " + card_activity.deck_map.size();
tv.setText(current_page);
tv1.setText(String.valueOf(page_index));
CardContainerFragment cardContainerFragment = new CardContainerFragment();
cardContainerFragment.current_index_front = page;
cardContainerFragment.current_index_back = page;
String card_front_string = card_activity.arraylst.get(page);
CardContainerFragment.complete_text_front = card_front_string +" \n \n + \n Tap now to flip this card.";
Bundle b = new Bundle();
b.putInt("index",page);
CardContainerFragment.complete_text_back = card_activity.deck_map.get(card_front_string);
cardContainerFragment.setArguments(b);
return cardContainerFragment;
}
#Override
public int getCount() {
int len = card_activity.deck_map.size();
return len;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Please let me know what I am doing wrong here.
Thanks in advance
Finally I am able to do this with some efforts.
After searching, I get to know that getItems (The method in CardPagerAdapter) is called two times because Android creates one extra fragments for smooth transition and I was sending or getting wrong position of fragments from getItems.
By letting the android to create one extra fragment and by sending correct position I am able to solve this issue.
Here is my updated code
public class CardActivity extends android.support.v4.app.FragmentActivity {
public TextView tv;
public static String index=null;
public static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.card_example);
tv = (TextView)findViewById(R.id.tv_card_number);
FragmentManager m = getFragmentManager();
CardPagerAdapter adapter = new CardPagerAdapter(m);
index = getIntent().getStringExtra("index");
card_activity.cardCounter = Integer.parseInt(index);
int count = card_activity.cardCounter;
int final_count = count+1;
String current_page = final_count+" of "+card_activity.deck_map.size();
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(card_activity.cardCounter);
String current_page_temp =final_count+" of " + card_activity.deck_map.size();
tv.setText(current_page_temp);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.e("aaa",position+"");
String current_page = position+1 + " of " + card_activity.deck_map.size();
tv.setText(current_page);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}catch(Exception e){
e.printStackTrace();
}
}
public class CardPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
CardContainerFragment cardContainerFragment = new CardContainerFragment();
Bundle b = new Bundle();
b.putInt("index",i);
cardContainerFragment.setArguments(b);
return cardContainerFragment;
}
#Override
public int getCount() {
int len = card_activity.deck_map.size();
return len;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
==================================================================
public class CardContainerFragment extends Fragment {
private boolean cardFlipped = false;
int current_index=0;
static int pos = 0;
public CardContainerFragment() {
/*setHasOptionsMenu(true);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_container, container, false);
LinearLayout ll = (LinearLayout)rootView.findViewById(R.id.layout);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
pos = getArguments().getInt("index");
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment().newInstance(pos))
.commit();
card_activity.tempCounter = card_activity.tempCounter+1;
return rootView;
}
public void flipCard() {
Fragment newFragment = null;
CardFrontFragment cardFrontFragment = null;
CardBackFragment cardBackFragment = null;
if (cardFlipped) {
newFragment = CardFrontFragment.newInstance(CardActivity.mViewPager.getCurrentItem());
} else {
newFragment = cardBackFragment.newInstance(CardActivity.mViewPager.getCurrentItem());
}
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
cardFlipped = !cardFlipped;
}
public static class CardBackFragment extends Fragment {
public CardBackFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView_back = inflater.inflate(R.layout.fragment_card_back, container, false);
TextView textview_back = (TextView)rootView_back.findViewById(R.id.card_back);
textview_back.setMovementMethod(new ScrollingMovementMethod());
String text = getArguments().getString("back_text");
textview_back.setText(text);
return rootView_back;
}
static CardBackFragment newInstance(int position) {
CardBackFragment cardBackFragment = new CardBackFragment();
Bundle args = new Bundle();
String card_front_string = card_activity.arraylst.get(position);
String text = card_activity.deck_map.get(card_front_string);
args.putString("back_text", text);
cardBackFragment.setArguments(args);
return cardBackFragment;
}
}
public static class CardFrontFragment extends Fragment {
public CardFrontFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView_front = null;
rootView_front = inflater.inflate(R.layout.fragment_card, container, false);
TextView textview_front = (TextView)rootView_front.findViewById(R.id.card_front);
String text = getArguments().getString("front_text");
textview_front.setText(text);
return rootView_front;
}
static CardFrontFragment newInstance(int position) {
CardFrontFragment cardFrontFragment = new CardFrontFragment();
Bundle args = new Bundle();
String card_front_string = card_activity.arraylst.get(position);
String text = card_front_string +" \n \n + \n Tap now to flip this card.";
args.putString("front_text", text);
cardFrontFragment.setArguments(args);
return cardFrontFragment;
}
}
}
As #david-rawson says
Don't use static fields CardActivity.mViewPager. See https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Reason for this is that the ViewPager might/will create the views of your fragments before they are displayed to ensure you get that smooth animation that people love ViewPagers for. So the mViewPager calls a number of fragments createView() function at the same time, and at that time the mViewPager has an index for .getCurrentItem() which goes to the CardContainer on the page being viewed.
A better option would be for you to pass CardContainerFragment a String argument with the value for "completeText" which you want it to display whenever it creates either CardBackFragment or CardFrontFragment.
Go through this for more details.
You just have to set data to text view which is used in CardFrontFragment.
Here when ever a swipe happens onCreateView() of CardContainerFragment is called.
You are adding CardFrontFragment every time when onCreateView() is called. you need to use text view of CardFrontFragment instead of using textview of activity.
Just replace CardActivity.tv.setText(current_page);
with textView.setText(current_page);
Make sure the textview you have used in CardFrontFragment is available at class level.
you are using static fragments so textview must be static.
private static TextView textView=null;
Hope this will work for you :)
Have you tried this:
tv.post(new Runnable() {
#Override
public void run() {
CardActivity.tv.setText(current_page);
}
});
I did something similar wihtin my App, and I manage the display of my TextView into the OnCreateView, with a switch case.
I tried to implent your code but did not have all your materials (like custom animator).
You should then try something like that:
public class CardContainerFragment extends AppCompatActivity {
private boolean cardFlipped = false;
static TextView textview;
/*public CardContainerFragment() {
setHasOptionsMenu(true);
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_name);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
/*
The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
flipCard();
#Override
public void onPageSelected(int position) {
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_welcome, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Initializing data
Context context = getContext();
View rootView = inflater.inflate(R.layout.fragment_card, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.txtView);
int fragment = getArguments().getInt(ARG_SECTION_NUMBER);
switch (fragment)
{
case 1: //front card
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
String complete_text = card_front_string +" \n \n + \n Tap now to flip this card.";
textview.setText(complete_text);
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
case 2: //back card
TextView textview = (TextView)rootView.findViewById(R.id.card_back);
textview.setMovementMethod(new ScrollingMovementMethod());
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
String deck_data = card_activity.deck_map.get(card_front_string);
textview.setText(deck_data);
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
default:
return rootView;
}
}
}
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int page = CardActivity.mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = page_index + " of " + card_activity.deck_map.size();
CardActivity.tv.setText(current_page);
super.handleMessage(msg);
}
};
public void flipCard() {
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}
The textView is displayed on your page, and when selecting the change, the content of your textview will be changed.

android value passing adapter to fragment

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

How to pass Parcelable to two or more Activities or Fragments?

I can pass Parcelable to one Fragment or Activities but I can't pass Parcelable to two or more Fragment or Activities.
I have a ListView in Fragment when i click list item, list item details will be send to GetFragment1, GetFragment1 I have button to show more details of list item, I want to get Parcelable from SendFragment in GetFragment2 and GetFragment3.
This is Test.java
import android.os.Parcel;
import android.os.Parcelable;
public class Test implements Parcelable {
private int studentNumber;
private String studentName;
private String studentFamily;
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentFamily() {
return studentFamily;
}
public void setStudentFamily(String studentFamily) {
this.studentFamily = studentFamily;
}
public Test() {
}
public Test(Parcel read) {
studentNumber = read.readInt();
studentName = read.readString();
studentFamily = read.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel write, int flags) {
write.writeInt(studentNumber);
write.writeString(studentName);
write.writeString(studentFamily);
}
public static final Parcelable.Creator<Test> CREATOR =
new Parcelable.Creator<Test>() {
#Override
public Test createFromParcel(Parcel source) {
return new TestP(source);
}
#Override
public Test[] newArray(int size) {
return new TestP[size];
}
};
}
In FragmentSend.java I want to send data to FragmentGet1.java and FragmentGet2.java and FragmentGet3.java, this is the code:
public class FragmentSend extends ListFragment {
// Classes
TestReadData readData;
TestDataSource dataSource;
private List<Test> listTest;
public FragmentSend() {
// Required empty public constructor
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_send, container, false);
readData = new TestReadData(getContext());
dataSource = new TestDataSource(getContext());
refreshStudentList(inflater);
return layout;
}
public void refreshStudentList(LayoutInflater inflater) {
listTest = readData.getAllStudentRows();
ArrayAdapter<Test> testAdapter = new TestFragmentListAdapter(inflater.getContext(), listTest);
setListAdapter(testAdapter);
}
#Override
public void onResume() {
super.onResume();
dataSource.open();
}
#Override
public void onPause() {
super.onPause();
dataSource.close();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Test model = listTest.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("Student", model);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragmentGet1 = new FragmentGet1();
Fragment fragmentGet2 = new FragmentGet2();
Fragment fragmentGet2 = new FragmentGet3();
fragmentGet1.setArguments(bundle);
fragmentGet2.setArguments(bundle);
fragmentGet3.setArguments(bundle);
fragmentTransaction.replace(R.id.frame_container, fragmentGet1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
in GetFragment1.java I can get Parclable successfully but in two other Fragments (GetFragment2.java and GetFragment3.java) the bundle will be null!
This is GetFragment1.java code for getting Parcelable:
I use this code for other two Fragments.
Bundle bundle;
bundle = this.getArguments();
if (bundle != null) {
model = bundle.getParcelable("Student");
if (model != null) {
Log.i(LOG_TAG, String.valueOf(String.valueOf(model.getStudentNumber());
}
} else {
Log.i(LOG_TAG, "LogDetailsFragment 'bundle' is null!");
}
how can i send Parcelable for more Fragments?
Ok, your problem is in the sequence of things. In this part of your code:
Fragment fragmentGet1 = new FragmentGet1();
Fragment fragmentGet2 = new FragmentGet2();
Fragment fragmentGet2 = new FragmentGet3();
fragmentGet1.setArguments(bundle);
fragmentGet2.setArguments(bundle);
fragmentGet3.setArguments(bundle);
You are creating instances of all the 3 fragments, but then only using the instance of FragmentGet1. The other ones are not used. Later, when you create another instance of any of those Fragments, it will not have the args because it is a totally separate object.
That you need is to pass the bundle forward each time you create a new Fragment. If you want to create it from within an already-created fragment, it will look somewhat like this:
public void showNextFragment() {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragmentGet2 = new FragmentGet2();
if(this.getArguments() != null)
fragmentGet2.setArguments(this.getArguments());
fragmentTransaction.replace(R.id.frame_container, fragmentGet2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Put it into your FragmentGet1 and let me know if this if what you need :-)
EDIT:
To pass the Student object to an Activity, just do something like this:
Student s = //get it here
Bundle b = new Bundle();
b.putParcelable("student", s);
Intent i = new Intent(getActivity(), ThatOtherActivity.class);
i.putExtra("extraWithStudent", b);
startActivity(i);
And then to read the data in the Activity:
Intent incomingIntent = getIntent();
Bundle b = incomingIntent.getBundleExtra("extraWithStudent");
Student s = (Student) b.getParcelable("student");

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

How to send data from Activity to Fragment

I know there are many topics about this here. I have also read documentation many times but I can't find the best way to pass data from activity to fragment.
I want to be able to show the results of my Searchable activity in two differents layouts (list and map) using swipe Views with tabs. I have to pass 2 data to the fragments: "currentLocation" which is the current user location and "result" which is a list of objects.
I have omited some parts of my code to make it more understandable.
SearchableActivity.java
public class SearchableActivity extends ActionBarActivity implements TabListener {
List<PlaceModel> result = new ArrayList<PlaceModel>();
private SearchView mSearchView;
private String currentLocation;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchable);
final ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(actionBar.newTab().setText("List").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Map").setTabListener(this));
// get currentLocation here
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
final String query = intent.getStringExtra(SearchManager.QUERY);
// get result here
}
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
PlaceListFragment.java
public class PlaceListFragment extends Fragment {
ListView listViewData;
PlaceAdapter placeAdapter;
List<PlaceModel> result = new ArrayList<PlaceModel>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
Bundle args = getArguments();
listViewData = (ListView) rootView.findViewById(android.R.id.list);
// I will pass result and currentLocation here
placeAdapter = new PlaceAdapter(getActivity(), R.layout.fragment_list_item, result, currentLocation);
listViewData.setAdapter(placeAdapter);
return rootView;
}
}
AppSectionsPagerAdapter.java
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Bundle data = new Bundle();
switch(arg0) {
case 0:
PlaceListFragment fragment1 = new PlaceListFragment();
fragment1.setArguments(data);
return fragment1;
default:
PlaceListFragment fragment2 = new PlaceListFragment();
fragment2.setArguments(data);
return fragment2;
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
Find fragment in Activity onCreate and set data to a method you write in your fragment:
ExampleFragment rf = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.exampleFragment);
if(rf!=null){
rf.setExample(currentExample);
}
"CurrentExample" is whatever you want to send in to your "setExample" method in your fragment.
public void setExample(ExampleObject currentExample){
currentExampleInFragment = currentExample;
}
You can use the data in onActivityCreated method of Fragment.
Not sure is this is a good solution or not, but I found it the easiest one for passing objects.
Usually the activities will have a reference to their fragments. In your SearchableActivity.java are you also loading PlaceListFragment.java either in setContentView(activity_searchable.xml); or you need to create a instance of the fragment and add/replace a fragment using FragmentTransaction.
you can find a good example here on how to communicated between fragments or between activity & fragment.
Training link
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
see detail answer here..
"send data from Activity to Fragment"
Activity:
Bundle bundle = new Bundle();
bundle.putString("message", "Alo Stackoverflow!");
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
String myValue = bundle.getString("message");
...
...
...
}
or
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String myValue = this.getArguments().getString("message");
...
...
...
}
Create one Session model class and in Activity set the values you want to data needs to be send then in Fragment you can get that values from Session model class
eg. from your activity u can set like this.
AllEventDetails.getInstance().setEvent_description(event_Description);
AllEventDetails.getInstance().setDj_name(dj_name);
AllEventDetails.getInstance().setMusic_theme(music_theme);
AllEventDetails.getInstance().setClub_name(club_name);
AllEventDetails.getInstance().setDate(event_date);
AllEventDetails.getInstance().setBanner_image_path(banner_image_path);
AllEventDetails.getInstance().setEvent_title(event_title);
and from your Fragment u can retrive like this.
AllEventDetails.getInstance().getClub_name()
.........
Creating Session model class is like this.
public class AllEventDetails {
private static AllEventDetails mySession ;
private String event_description;
private String dj_name;
private String music_theme;
private String club_name;
private String date;
private String banner_image_path;
private String event_title;
private AllEventDetails() {
event_description = null;
dj_name = null;
music_theme = null;
club_name = null;
date = null;
banner_image_path = null;
event_title = null;
}
public static AllEventDetails getInstance() {
if( mySession == null ) {
mySession = new AllEventDetails() ;
}
return mySession ;
}
public void resetSession() {
mySession=null;
}
public String getEvent_description() {
return event_description;
}
public void setEvent_description(String event_description) {
this.event_description = event_description;
}
public String getDj_name() {
return dj_name;
}
public void setDj_name(String dj_name) {
this.dj_name = dj_name;
}
public String getMusic_theme() {
return music_theme;
}
public void setMusic_theme(String music_theme) {
this.music_theme = music_theme;
}
public String getClub_name() {
return club_name;
}
public void setClub_name(String club_name) {
this.club_name = club_name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getBanner_image_path() {
return banner_image_path;
}
public void setBanner_image_path(String banner_image_path) {
this.banner_image_path = banner_image_path;
}
public String getEvent_title() {
return event_title;
}
public void setEvent_title(String event_title) {
this.event_title = event_title;
}
}

Categories

Resources