I have 2 activities MainActivity and DetailActivity, if I click in the ListView in MainActivity will intent to DetailActivity with content "id", in DetailActivity I have 2 fragment (TabLayout-ViewPager).
My question is: How can fragment get "id" from that intent above???
Fragment in android
,If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.for more detail please read this stack overflow answer
private int mId;
private static final String ID = "id";
public static DetailsFragment newInstance(int id) {
DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
get values in oncreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
//mId is variable which contain (YourActivity)MainActivity value.you can use in fragment.
mId = getArguments().getInt(ID);
}
//call in your YourActivity(MainActivity) in oncreate method
int id = yourid;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,DetailFragment.newInstance(id)).commit();
from Android Developer's Fragment Page
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
// add fragment to the fragment manager's stack
Like #cricket_007 says, create a factory method in your fragment and pass the data through bundle arguments consider the example below
public static YourFragment newInstance(Bundle args) {
Yourfragment fragment = new YourFragment();
Bundle bundle = args;
// Or if your args is a variable data for example a string
// use Bundle bundle = new Bundle(); bundle.putString("extra_name",value);
// Now set the fragment arguments
fragment.setArguments(bundle);
return fragment;
}
And now anywhere in your fragment you can do
Bundle args = getArguments();
// and access your extra by args.getString("extra_name"); ...
Related
I have been looking at various examples on how to pass data and they all had a similar structure
Bundle bundle = new Bundle();
bundle.putString("params", "My String data");
MyFragment frag= new MyFragment();
frag.setArguments(bundle);
But it says my fragment does not contain a definition for setArguments
What am i doing wrong here?
And is there another method to pass data?
Edit:
When i run through this bit of code it says the bundle is null
Bundle bundle = this.Arguments;
if (bundle != null)
{
string FirstName = bundle.GetString("FirstName");
Toast.MakeText(this.Activity, "Yay it Worked", ToastLength.Short).Show();
}
In the Xamarin/C# normalization of the Android Fragment API, setArguments and getArguments becomes a C# property (Arguments):
frag.Arguments = bundle;
Use newInstance() design:
public class YourFragment extends Fragment {
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString("param1", param1);
args.putString("param2", param2);
fragment.setArguments(args);
return fragment;
}
}
and then in your activity:
YourFragment frag = YouFragment.newInstance("a", "b");
Hope you get the idear.
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.
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
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
}
}
activity_one.xml
<fragment
android:id="#+id/fragment"
class="com.emoontech.waternow.FragmentA"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
FragmentA
public class FragmentA extends Fragment{
public static FragmentEditEvent newInstance(String param1, String param2) {
FragmentEditEvent fragment = new FragmentEditEvent();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
}
//From Another Activity on button click
Intent intent = new Intent(this, ActivityA.class);
intent.putString("param1","val1");
intent.putString("param2","val2");
startActivity(intent);
//How to send these two values to FragmentA?
answer i made there https://stackoverflow.com/a/32748751/3301009 to share data between activities is very general and can also work for fragments
try this
// From ActivityA
// retrieve the content of the intent from the previous activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment); // set content view to layout
String param1Text= getIntent().getStringExtra("param1");
String param2Text = getIntent().getStringExtra("param2");
// this will pass the parameter to the fragment
Fragment frament = FragmentA.newInstance(param1Text, param2Text);
// use the fragment for what you desire
}
Found that its not possible to pass argument to the faragment directly but alternative is to use fragment manager and do findFragmentById() in activity to get fragment and set the date as needed.
Edit:
If I declare a fragment in an XML layout, how do I pass it a Bundle?
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!