How to send data from Activity to Fragment - android

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

Related

Trying to Pass data from Activity to Fragment

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)

Fragment in ViewPager using FragmentPagerAdapter is blank the first time activity is loaded

I'm creating an app with vertical page adapter using FragmentStatePagerAdapter. The big issue i'm facing is, data is not displayed on the textview on first app launch but is displayed on scrolling the page. I believe the fragment view is delaying to create textview because, on my LoadAlbumDataCompleted() function inside Fragmentone.class, i'm able to print the data returned or also output via toast but is not getting populated to the textview.
Kindly help.
MainActivity.class
public class MainActivity extends FragmentActivity implements LoadAalbumsTotalListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MainActivityVSlideAdapter(this, getSupportFragmentManager(), NUMBER_OF_PAGES);
mPager.setAdapter(mAdapter);
LoadTotalAlbumsNum.BindAlbumsTotalListener(this);
}
#Override
public void OnLoadAlbumsCompleted(String total) {
if(total.trim().equalsIgnoreCase("")){
NUMBER_OF_PAGES=0;
}else{
NUMBER_OF_PAGES=Integer.parseInt(total.trim());
}
mAdapter = new MainActivityVSlideAdapter(this, getSupportFragmentManager(), NUMBER_OF_PAGES);
mPager.setAdapter(mAdapter);
}
}
MainActivityVSlideAdapter.class Adapter
public class MainActivityVSlideAdapter extends FragmentStatePagerAdapter {
static int NUMBER_OF_PAGES;
private Context con;
public MainActivityVSlideAdapter(Context con, FragmentManager fm, int NUMBER_OF_PAGES) {
super(fm);
this.con=con;
this.NUMBER_OF_PAGES=NUMBER_OF_PAGES;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
#Override
public Fragment getItem(int position) {
return FragmentOne.newInstance(position);
}
}
Fragmentone.class
public class FragmentOne extends Fragment implements LoadAlbumDataListener {
private static final String MY_NUM_KEY = "num";
private int mNum;
private TextView SaloonName;
private TextView location;
// You can modify the parameters to pass in whatever you want
public static FragmentOne newInstance(int num) {
FragmentOne f = new FragmentOne();
Bundle args = new Bundle();
args.putInt(MY_NUM_KEY, num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get argument from
mNum = getArguments() != null ? getArguments().getInt(MY_NUM_KEY) : 0;
session=new Session(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one, container, false);
Methods methods=new Methods(getActivity());
// v.setBackgroundColor(mColor);
SaloonName = v.findViewById(R.id.SaloonName);
location=v.findViewById(R.id.location);
new LoadAlbumData(getActivity()).execute(getString(R.string.urlAddress)+"load-album-data.php", String.valueOf(mNum));
LoadAlbumData.BindLoadAlbumDataListener(this);
return v;
}
#Override
public void LoadAlbumDataCompleted(String s) {
JSONArray jsonPicsArray = null;
JSONObject jsonObj;
String BusinessLocation=null;
try {
jsonPicsArray = new JSONArray(s);
businessName = jsonObj.getString("businessName");
BusinessLocation = jsonObj.getString("location");;
}
Toast.makeText(getActivity(), businessName, Toast.LENGTH_LONG).show();
SaloonName.setText(businessName);
location.setText(BusinessLocation);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
From your code, it looks like, you are not setting the LoadAlbumDataListener correctly. Instead of statically setting the listener. Pass reference in constructor of your LoadAlbumData Asynctask
remove this line
LoadAlbumData.BindLoadAlbumDataListener(this);
replace
new LoadAlbumData(getActivity()).execute(getString(R.string.urlAddress)+"load-album-data.php", String.valueOf(mNum));
with
new LoadAlbumData(getActivity(), this).execute(getString(R.string.urlAddress)+"load-album-data.php", String.valueOf(mNum));
Modify your asynctask to have reference of LoadAlbumDataListener
Also as a good practice, never store strong reference of activity or fragment in your asynctask. Use WeakReference.

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

Android - Sending data from fragment to fragment using swipeview

Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.

Get EditText value on different fragment

I am trying to get some text from editTexts on different fragments. So what I do first is define my mPager and mPagerAdapter:
a_Atenuacion Activity
public class a_Atenuacion extends FragmentActivity{
private static final int NUM_PAGES = 3;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_dat_viewpager);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new a_Dat_Inicio1();
case 1:
return new a_Dat_Inicio2();
case 2:
return new a_Dat_Inicio3();
}
return null;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
Then I get my 3 fragments classes (Both 1st and 2nd layouts have an editText, but the 3rd one has an editText and a button). The button function is that when I am in the last fragment (fragment3) it take info form (different editTexts) and send to another activity.
a_Dat_Inicio1 Fragment
public class a_Dat_Inicio1 extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_dat_inicio1, container, false);
return view;
}
}
a_Dat_Inicio3 Fragment
public class a_Dat_Inicio3 extends Fragment {
EditText edit3;
EditText edit2;
EditText edit1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.a_dat_inicio3, container, false);
edit1 = (EditText)getActivity().findViewById(R.id.editText1);
final String edit11 = edit1.getText().toString();
edit2 = (EditText)getActivity().findViewById(R.id.editText2);
final String edit22 = edit2.getText().toString();
edit3 = (EditText)view.findViewById(R.id.editText3);
final String edit33 = edit3.getText().toString();
Button but=(Button) view.findViewById(R.id.button);
but.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//Creamos el bundle
Bundle bundle = new Bundle();
//Le ponemos la variable parametro con el contenido (key, valor)
bundle.putString("edit3", edit33);
bundle.putString("edit2", edit22);
bundle.putString("edit1", edit11);
Intent net= new Intent(v.getContext(),Prueba1.class);
net.putExtras(bundle);
startActivity(net);
}
});
return view;
}
}
Finally I get bundle on another activity (Prueba1.class) and it is curious that I only get result for editText1 (on 1st fragment) and rest are null.
Can anybody give me a help?
Thanks in advance.
finally I get over an interface, that is the only way I think to get soemthing on already defined fragments.
My code get like this:
1st define an interface
public interface OnEditTextChanged {
public void onEditPressed1(String edit1);
public void onEditPressed2(String edit1);
public void onEditPressed3(String edit1);
Then fragment activity:
public class a_Dat_Inicio1 extends Fragment {
EditText edit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_1dat_inicio1, container, false);
init (view);
return view;
}
OnEditTextChanged editListener;
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
editListener=(OnEditTextChanged) getActivity();
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()+"must implemnt onEditPressed");
}
}
private void init(View view) {
edit=(EditText) view.findViewById(R.id.editText1);
//cada vez que se modifique texto llamar
edit.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
final String edit11 = edit.getText().toString();
editListener.onEditPressed1(edit11);
}
});
And finally on our main activity, call the method:
public class a_Atenuacion extends FragmentActivity implements OnEditTextChanged {
String dat1;
String dat2;
String dat3;
private static final int NUM_PAGES = 3;
private PagerAdapter mPagerAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_1dat_viewpager);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
//HERE DO WHATEVER YOU WANT WITH THE DATA CAUGTH ON THE EDIT 1 METHOD
}
#Override
public void onEditPressed1(String edit1) {
if(mPager.getCurrentItem()==0){
dat1=edit1;
Toast bread = Toast.makeText(getApplicationContext(), "edit1", Toast.LENGTH_LONG);
bread.show();
}
}
HOPE this help someone!!!
In any way thanks!!!
Try this:
In your second fragment, pass the intent extras and your value. For example:
In you second fragment, do this :
Intent someintent = new Intent();
//Some first result
someintent.putExtra("your_value_one", your_value_one);
//Some Second result
someintent.putExtra("your_value_two", your_value_two);
//Some third result
someintent.putExtra("your_value_three", your_value_three);
getActivity().setResult(getActivity().RESULT_OK,someintent);
getActivity().finish();
In your other fragment, where you want this result, do this on your other fragment like this:
1) Make some method to get the info.
private void getInfo() {
//Note: The values are coming from a diff activity or fragment and so the strings should match.
Intent data = new Intent();
String first_value = data.getStringExtra("your_value_one");
String second_value = data.getStringExtra("your_value_two");
String third_value = data.getStringExtra("your_value_three");
Log.i("First Value: ", first_value);
Log.i("First Value: ", second_value);
Log.i("First Value: ", third_value);
}
After making this method, just call it on your onActivityCreated().
Now you can use those string however and wherever you want to. If you want to use those values anywhere else, make sure to define you strings at the very start so that you can use the values anywhere.
Hope this answer helps .. :)

Categories

Resources