android passing and retrieving extra from activity to fragment - android

I have an activity where the user press a button and then is send to a fragment, but I wish to pass an extra for the use of the fragment:
activity A(where is the button):
public OnClickListener publish = new OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),ActivityB.class);
intent.putExtra("friendIdRowID", rowID);
startActivity(intent);
}
};
Activity B is loading the fragment(where I wish to retrieve the extra "friendIdRowID"),
the fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main2, container, false);
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null)
{
String myString = extras.getString("friendIdRowID");
}
}
But it is not working, what can I do to pass and retrieve the extra? thanks.

You need to use the setArguments() method of Fragment to pass information into your fragment. In the activity that creates the fragment, do something like this:
YourFragment f = new YourFragment();
Bundle args = new Bundle();
args.putString("friendIDRowID", getIntent().getExtras().getString("friendIDRowID"));
f.setArguments(args);
transaction.add(R.id.fragment_container, f, "tag").commit();
Then, override the onCreate() method of your Fragment and do the following:
Bundle args = getArguments();
String myString = args.getString("friendIdRowID");
Like extras for an Activity, you can add as many things to your arguments bundle as you wish. Hope this helps!

Related

Send Intent From Activity To Fragment

I want to send intent from activity to fragment. I know how to send from fragment to activity just like this
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
but now i want to send from activity to fragment. I don't necessarily need to start the fragment i just want to make one of the id in my activity accessible in my fragment.
From your activity, you send your data, using bundle:
Bundle newBundle = new Bundle();
newBundle.putString("key", "text");
YourFragment objects = new YourFragment();
objects.setArguments(newBundle);
Your fragment class in onCreateView function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
if(getArguments() != null){
String yourText = getArguments().getString("key");
}
return inflater.inflate(R.layout.your_fragment, container, false);
}`
Passing the data from activity to fragment
Bundle bundle = new Bundle();
bundle.putString("params", "String data");
// set MyFragment Arguments
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
Receiving the data in the fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("params");
}
}

How do you pass an intent from activity to a fragment that is already opened

This is the answer that I got from other topic and applied it to my codes:
From Activity you send data with intent as:
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);
}
These are the codes that I applied, it is not working somehow. The fragment is already opened at the start.
public void onInfoWindowClick(Marker marker) {
if (tag.equals("Click to show all routes in this point")) {
Bundle bundle = new Bundle();
bundle.putString("route1", "Divisoria - San Juan");
// set Fragmentclass Arguments
hideShowFragment fragobj = new hideShowFragment();
fragobj.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
Fragment intersectionFragment = manager.findFragmentById(R.id.fragmentContainer2);
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.add(R.id.fragmentContainer2, fragobj);
ft.show(intersectionFragment);
ft.commit();
}
}
The codes in my onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hide_show, container, false);
if (!routes.equals(none)) {
routes = getArguments().getString("route1");
} else {
routes = "Food";
}
return view;
}
What I want to happen is that the fragment will always update to what marker Tag that I click on the map. In other words, pass the string to the fragment (that is opened) and update it.
I do not want to use startActivityForResult because I can't move around the map if I don't use fragments. Is there a way to send result from activity to fragment that is already opened and running? If none, then how can I make the fragment not running from the start (using supportFragmentManager)? I only know is to hide it
If you have running Fragment and want to pass some data to it, you should create some way to communicate. For that purposes, you can use Observer pattern.
First of all create interface inside Activity if you want to pass data to Fragment:
public interface OnInfoClickedListener {
void onInfoClicked(String info);
}
Implement this interface inside Fragment:
#Override
public void onInfoClicked(String info) {
infoTextView.setText(info);
}
Now, inside your Activity, create variable to store this interface implementation:
private OnInfoClickedListener listener;
And when instantiating Fragment, save instance of it to variable:
InfoFragment fragment = InfoFragment.newInstance();
listener = fragment;
And when needed just provide data through this interface:
listener.onInfoClicked("Info - " + UUID.randomUUID());

How to pass arguments to a Fragment which is currently active?

I have an activity, which instantiates 4 different fragments based on button clicks.
I have to pass additional values to my fragment which is currently active.
Initially, when I pass values via setArguments, the values are being passed. But 2nd time the values are not passed to Fragment.
I tried to Log and put breakpoints in onCreate and onCreateView methods, but these methods are not being called at all 2nd time.
Here is my code
Code in Activity
Bundle bundle = new Bundle();
bundle.putInt("from", "1");
bundle.putString("label","One");
MyFragment1 myFragment1 = new MyFragment1();
myFragment1.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment1, myFragment1)
.commitAllowingStateLoss();
Code in Fragment
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getArguments();
if(b!=null)
{
}
}
From Activity
Bundle bundle = new Bundle();
bundle.putInt("from", "1");
bundle.putString("label","One");
// 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 label = getArguments().getString("label");
int i=getArguments().getInt("from");
return inflater.inflate(R.layout.fragment, container, false);
}
Found the solution
I gave this line of code in onCreate in Activity.
MyFragment1 myFragment1 = new MyFragment1();
I had to reinstatitate before passing it to the fragment.

How can i pass adapter to fragment like in intent

I am new to android and I am trying to call my MapFragment from adapter after on click using intent below is my code
Below is adapter code:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final BusInfo info = getItem(position);
View view = LayoutInflater.from(context).inflate(R.layout.bus_only_list,null);
TextView busname;
busname = (TextView) view.findViewById(R.id.busname);
busname.setText(info.name);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = context.getSharedPreferences("busInfo",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("bus_name",info.name);
editor.commit();
Intent intent = new Intent(context, MapsFragment.class);
intent.putExtra("name",info.name);
context.startActivity(intent);>
}
});
return view;
}
I want to pass to mapfragment using intent but it redirect to MainActivity instead of MapFragment. How can I stop transferring to MainActivity?
Thank you.
A common pattern to passing a value to a Fragment is using newInstance method. In this method you can set Argument to fragment as a means to send the value.
First, create the newInstance method:
public class YourFragment extends Fragment {
...
// Creates a new fragment with bus_name
public static YourFragment newInstance(String busName) {
YourFragment yourFragment = new YourFragment();
Bundle args = new Bundle();
args.putString("bus_name", busName);
yourFragment.setArguments(args);
return yourFragment;
}
...
}
Then you can get the value in onCreate:
public class YourFragment extends Fragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the value from arguments
String busName = getArguments().getString("bus_name", "");
}
...
}
You can set the value to the Fragment from your activity with:
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
YourFragment yourFragment = YourFragment.newInstance("bus_name_value");
fragTransaction.replace(R.id.fragment_place_holder, yourFragment);
fragTransaction.commit();
You can use the above codes to send the value in Fragment initialization.
If you want to set the value to the already instantiated fragment, you can create a method then invoke the method to set the value:
public class YourFragment extends Fragment {
...
public setBusName(String busName) {
// set the bus name to your fragment.
}
...
}
Now, In the activity, you can invoke it with:
// R.id.yourFragment is the id of fragment in xml
YourFragment yourFragment = (YourFragment) getSupportFragmentManager()
.findFragmentById(R.id.yourFragment);
yourFragment.setBusName("bus_name_value");
You cannot pass an intent to a Fragment. Try using a Bundle instead.
Bundle bundle = new Bundle();
bundle.putString("name", info.name);
mapFragment.setArguments(bundle)
In your Fragment (MapsFragment) get the Bundle like this:
Bundle bundle = this.getArguments();
if(bundle != null){
String infoName = bundle.getString("name");
}
As guys mentioned before:
1. Use callback or just casting on your context (your activity must handle changing fragments itself).
2. To change fragments use activity's FragmentManager - intent is used to start another activity.
Fragments Documentation

Launch fragment map with address to search

Im having a issue I dont know how to resolve.
I have a fragment with a editText and a button.
The button launches a fragment map like this:
public void onClick(View view) {
//Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
Home activity = (Home) getActivity();
if(activity != null)activity.openMapFragment();
break;
}
and the function openMapFragment():
public void openMapFragment(){
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
How would i do to send the text inserted on editText field as a address to look for on map fragment?
You should use bundle to pass data to a fragment :
public void openMapFragment(String args){
Fragment fragment = new gMapFragment();
Bundle bundle = new Bundle();
bundle.putString("foo", args);
fragment.setArguments(bundle);
replaceFragment(fragment);
}
And to retrieve data :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
String foo = getArguments() != null ? getArguments().getString("foo") : "";
//...
}

Categories

Resources