Trying to Pass data from Activity to Fragment - android

I'm new in Android Development here i'm trying to pass data from Activity to Fragment
"gameid" <-- i want to pass this data from Activity to Fragment
im using this code which is not working anyone tell me whats wrong in this code !!!!
Activity Class
public CardView matchCard;
ImageView gamebanner;
TabLayout tabLayout;
ViewPager2 pager2;
bettingpage_tabviewer adapter;
private ArrayList<MatchModel> gList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_betting_page);
String gameid = getIntent().getStringExtra(GAME_ID);
String banner = getIntent().getStringExtra(BANNER);
Bundle bundle = new Bundle();
bundle.putString("gameId", gameid);
// set Fragmentclass Arguments
matchtab fragobj = new matchtab();
fragobj.setArguments(bundle);
gamebanner = findViewById(R.id.gamebanner);
tabLayout = findViewById(R.id.bettingtabs);
pager2 = findViewById(R.id.bettingpagetab);
Glide.with(this).load(banner).into(gamebanner);
FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fm.beginTransaction();
final matchtab myFragment = new matchtab();
adapter = new bettingpage_tabviewer(fm, getLifecycle());
pager2.setAdapter(adapter);
tabLayout.addTab(tabLayout.newTab().setText("Match Tab"));
tabLayout.addTab(tabLayout.newTab().setText("Result Tab"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager2.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
pager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
tabLayout.selectTab(tabLayout.getTabAt(position));
}
});
}
}
Fragment Class
want to show "gameid" data in TextView named "demo"
public class matchtab extends Fragment {
private static final String ARG_PARAM1 = "gameId";
private String gameId;
RecyclerView matachrecyclerview;
private MyAdapter adapter;
private ArrayList<Model> gList;
public matchtab() {
// Required empty public constructor
}
public static matchtab newInstance(String gameId) {
matchtab fragment = new matchtab();
Bundle args = new Bundle();
args.putString("gameId", gameId);
fragment.setArguments(args);
return fragment;
}
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
gameId = this.getArguments().getString("gameId");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_matchtab, container, false);
TextView demo;
demo = v.findViewById(R.id.demotxt);
demo.setText(gameId);
// Recycler View
matachrecyclerview = v.findViewById(R.id.matchrecyclerview);
gList = new ArrayList<>();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("Match").child("game1");
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Model model = dataSnapshot.getValue(Model.class);
gList.add( new Model(model.title,model.amt));
Log.i("THE_CURRENT_USER:::", model.toString());
}
LinearLayoutManager im = new LinearLayoutManager((getContext()));
matachrecyclerview.setLayoutManager(im);
adapter = new MyAdapter(getContext(),gList);
matachrecyclerview.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return v;}
}
This Code is not working please tell me what's wrong in this code

You shouldn't use constructor in fragment, remove it. You're directly passing the parameters to fragment with bundle.put in activity, no need for newinstance in fragment then. Try to remove default constructor and newinstance and try again.

dude you created two instances of fragment and set the arguments to 1 but use 2 without arguments
Use first capital letter in class name and some useful names)
try to do
in your fragment:
public static MyFragment newInstance(String gameId) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString("gameId", gameId);
fragment.setArguments(args);
return fragment;
}
in your activity:
MyFragment.newInstance(gameId)

Related

Dynamic Data in TabLayout and Viewpager Fragment is Out of sync

I have a TabLayout, where the data is populated from web service which contain {"TOPS","LAUNDRY","BEDDING"...}.
This data is stored in a list which is passed into the adapter.
myTabAdapter = new MyTabAdapter(getSupportFragmentManager(),tabListings);
viewpager.setAdapter(myTabAdapter);
tabList.setupWithViewPager(viewpager);
And my TabAdapter.
public class MyTabAdapter extends FragmentStatePagerAdapter {
private ArrayList<TabListing> tabListings;
String item;
private Bundle bundle;
public MyTabAdapter(FragmentManager supportFragmentManager, ArrayList<TabListing> tabListings) {
super(supportFragmentManager);
this.tabListings = tabListings;
}
#Override
public Fragment getItem(int position) {
TabListing l = tabListings.get(position);
String a = l.getName();
bundle = new Bundle();
bundle.putString("item", a);
return OneFragment.newInstance(0, bundle);
}
#Override
public int getCount() {
return tabListings.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
TabListing l = tabListings.get(position);
String a = l.getName();
return a;
}
}
In the getItem() method I am passing the name using bundle to fragment with new instance method.
When the data gets into the fragment like "TOPS", it is to be passed in the database Reference field of Firebase to populate my recyclerview.
My problem is when i run the app, the get the data for "LAUNDRY" instead of "TOPS" in the first run. When I swipe 2 index forward to "BEDDING", the data is synced according to the tabs. I cannot understand what is the problem.
My Fragment class.
public class OneFragment extends Fragment {
private static String a;
RecyclerView recyclerview;
AdapterToActivity act;
Bundle args;
ListingAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mReference;
ContentLoadingProgressBar pBar;
int position;
ArrayList<ItemList> itm = new ArrayList<>();
public OneFragment() {
}
public static OneFragment newInstance(int position, Bundle item) {
Bundle args = item;
a = args.getString("item");
OneFragment fragment = new OneFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one, container, false);
recyclerview = v.findViewById(R.id.all_product_list);
pBar = v.findViewById(R.id.progress);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
recyclerview.setLayoutManager(layoutManager);
adapter = new ListingAdapter(getActivity(),itm,a);
args = getArguments();
RecyclerViewAdapterMethod();
return v;
}
#Override
public void onStart() {
super.onStart();
pBar.show();
adapter.notifyDataSetChanged();
pBar.hide();
}
private void RecyclerViewAdapterMethod() {
pBar.show();
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference(a);
mReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ItemList l;
l = dataSnapshot.getValue(ItemList.class);
itm.add(l);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
pBar.hide();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

Not able to pass String value through Bundle

This question is something serious for me , i need to someone help me regarding this. Actually i am creating an RSS feed app by combining navigation drawer and view pager tabbed activity. i want to pass a string value from one fragment to other fragment. here is the thing. It was working properly when it was with the navigation drawer activity but after combining with view-pager , String is not passing to other fragment through bundle, i can't find the error because its not showing any error,
This is from i am passing string
public class RssFragment extends Fragment implements OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
startService();
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService.class);
getActivity().startService(intent);
}
/**
* Once the {#link RssService} finishes its task, the result is sent to this BroadcastReceiver
*/
private BroadcastReceiver resultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>) intent.getSerializableExtra(RssService.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getDescription());
String string;
string=uri.toString();
result Des_1=new result();
FragmentManager fragmentManager1 =getActivity().getSupportFragmentManager();
fragmentManager1.beginTransaction().replace(R.id.content_main_layout_frame,Des_1 ).addToBackStack("fragBack").commit();
result ldf = new result();
Bundle args = new Bundle();
args.putString("YourKey", string);
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_main_layout_frame, ldf).commit();
}
#Override
public void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter(RssService.ACTION_RSS_PARSED);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(resultReceiver, intentFilter);
}
#Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(resultReceiver);
}
}
This is how i am receiving the string
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
Bundle bundle = getArguments();
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(bundle != null) {
String value = bundle.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
I pleasing someone to figure it out. i repeat it was working but now its not
It is another fragment
public class datafragment extends Fragment {
View view;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.sample,container,false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new sliderAdapter(getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
private class sliderAdapter extends FragmentPagerAdapter{
final String tabs[]={"tab1", "tab2","tab3"};
public sliderAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new RssFragment();
break;
case 1:
fragment = new RssFragment();
break;
case 2:
fragment = new RssFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
}
Try the below one,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.replace(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Remove both the transaction and add the below code instead,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.add(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Let me know if that helps!
Try this
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(savedInstanceState!= null) {
String value = savedInstanceState.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}

How to save loaded listView state in fragment?

I have one activity, fragment with listView and fragment with details for each listView item. I am getting fragments data from API. How should I save loaded date and listView position correctly to be able to restore it when I am returning back to the listView?
I tried to implement this solution Once for all, how to correctly save instance state of Fragments in back stack? but I cannot restore my listView correctly.
My MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
listFragment = new ListFragment();
fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, listFragment);
fragmentTransaction.commit();
if (savedInstanceState != null) {
//Restore the fragment's instance
listFragment = (ListFragment)getSupportFragmentManager().getFragment(savedInstanceState, "listContent");
}
...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "listContent", listFragment);
}
and ListFragment
public class ListFragment extends Fragment {
public static final String REQUEST_TAG = "ProjectListFragment";
private int page;
private View view;
private RelativeLayout loading ;
private PagingListView listView;
private PagingProjectListAdapter adapter;
private ArrayList<String> projects = new ArrayList<>();
private ArrayList<String> loadedProjects = new ArrayList<>();
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_list, container, false);
listView = (PagingListView) view.findViewById(R.id.projectsListView);
loading = (RelativeLayout) view.findViewById(R.id.loading);
//page = 1;
adapter = new PagingProjectListAdapter(getContext(), ListFragment.this);
listView.setAdapter(adapter);
listView.setHasMoreItems(true);
// Inflate the layout for this fragment
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// FIXME not used
listView.onFinishLoading(true, projects);
//Restore the fragment's state here
} else {
projects.clear();
page = 1;
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
new CustomVolleyAsyncTask().execute();
}
});
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentPosition", 0);
//Save the fragment's state here
}
public void itemClickMethod(View detailsView) {
LinearLayout linearLayout = (LinearLayout) detailsView;
String bid = linearLayout.getContentDescription().toString();
Bundle bundle = new Bundle();
String k = "ProjectID";
bundle.putString(k, bid);
DetailsFragment detailsFragment = new DetailsFragment();
detailsFragment.setArguments(bundle);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, detailsFragment, "DetailsFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
private class CustomVolleyAsyncTask extends SafeAsyncTask<List<String>> implements Response.Listener,
Response.ErrorListener {
public List<String> status = null;
private RequestQueue mQueue;
#Override
public List<String> call() throws Exception {
mQueue = CustomVolleyRequestQueue.getInstance(view.getContext())
.getRequestQueue();
String url = "http://www.myapi.com/api/v1/data/" + Integer.toString(page);
final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method
.GET, url,
new JSONObject(), this, this);
jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
// TODO rm redundant result
return status;
}
#Override
public void onErrorResponse(VolleyError error) {
// FIXME check no response case crash
//mTextView.setText(error.getMessage());
}
#Override
public void onResponse(Object response) {
try {
JSONArray projectsJSON = new JSONArray(((JSONObject) response).getString("projects"));
loadedProjects.clear();
for (int i=0; i < projectsJSON.length(); i++) {
loadedProjects.add(projectsJSON.getJSONObject(i).toString());
}
page++;
listView.onFinishLoading(true, loadedProjects);
if (loading.getVisibility() == View.VISIBLE && !listView.isLoading()){
listView.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}}}
}
currently, my savedInstanceState is always null, what am I missing?
I think, that your fragment created twice, when configuration changed. Here Staffan explain, why this happend. I resolve similar problem by this way (in activity onCreate):
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(TAG);
if(fragment==null)
fragmentManager.beginTransaction()
.add(R.id.container, NewsFragment.newInstance(),TAG)
.commit();

Pass ArrayList<String> between two activities that extends Fragment in Android

I have the activity1 that extends fragment. Here there is an ArrayList (FinalListToSend) that I want to pass to the other activity2
//ACTIVITY1
public class Page1Activity extends Fragment {
ArrayList<String> FinalListToSend;
public ArrayList<String> getList() {
return FinalListToSend;
}
public void setList(ArrayList<String> FinalListToSend) {
this.FinalListToSend = FinalListToSend;
}
public static Page1Activity newInstance() {
Page1Activity fragment = new Page1Activity();
return fragment;
}
public Page1Activity() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_page1, container, false);
return rootView;
}
}
I want to get the ArrayList in a second activity2
//ACTIVITY2
public static Page2Activity newInstance() {
Page2Activity fragment = new Page2Activity();
return fragment;
}
public Page2Activity() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.activity_page2, container, false);
Page1Activity page1= new Page1Activity();
ArrayList<String> ListToSave = new ArrayList<String>();
ListToSave=new ArrayList<String>(page1.FinalListToSend);
return rootView;
}}
I use view pager for this two activities.
I use this code and when I debug the FinalListToSend gets the items correctly when I am in Page1Activity, but when I press the button on PageActivity the FinalListToSend gets null.Any idea to get the array from the second activity?
Did you try with Bundle
Page2Activity tf = new Page2Activity ();
Bundle bundle = new Bundle();
bundle.putString("user_id", usersid);
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
To get bundle data
usersid = getArguments().getString("user_id");
And for Arraylist you can use
bundle.putStringArrayList("alist", yourarraylist);
Finally I got it.Needs to set the arraylist in the main activity as Final static
public class MainActivity extends AppCompatActivity {
private static ArrayList<String> FinalListToSend=new ArrayList<>();
public ArrayList<String> getList() {
return FinalListToSend;
}
public void setList(ArrayList<String> FinalListToSend) {
this.FinalListToSend = FinalListToSend;
}
and then set it from the first fragment
public class Page1Activity extends Fragment {
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> listErgasies = new ArrayList<String>();
listErgasies.add("DATA");
MainActivity MA= new MainActivity();
MA.setList(listErgasies);});
}
and get it from the second fragment
public class Page2Activity extends Fragment {
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> ListToSave = new ArrayList<String>();
MainActivity MA= new MainActivity();
ListToSave=new ArrayList<String>(MA.getList());}
// Toast.makeText(getActivity(),ListToSave.toString(),Toast.LENGTH_SHORT).show();
});}
1) pass the arraylist listErgasies
from activity 1 to activity 2
How to pass ArrayList<CustomeObject> from one activity to another?
2) show it as a listView again

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