I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);
DetailActivityFragment fragment = new DetailActivityFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_EXTRA, message);
fragment.setArguments(bundle);
}
I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments() from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
} else if (bundle == null) {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
The upper method displays a Toast message "Error" when I run the app...
The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:
public static myFragment newInstance(String param1, String param2) {
myFragment fragment = new myFragment ();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
And then on create set your global arguments:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
on your main activity you will create the fragment like
myFragment __myFragment = myFragment.newInstance("test","test");
That should work
This is a correct approach
Send (in the Activity):
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
final DetailActivityFragment frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);
final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);
ft.commit();
Receive (in the Fragment):
final Bundle bdl = getArguments();
String str = "";
try
{
str = bdl.getString("yourKey");
}
catch(final Exception e)
{
// Do nothing
}
Related
I want to pass parameters from activity to fragment.
This is the code from the activity:
public class MatchActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match);
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
MarqueFragment fragobj = new MarqueFragment();
fragobj.setArguments(bundle);
}
}
This is the code from the fragment:
public class MarqueFragment extends Fragment {
#Override
public void onCreate ( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
View convertView=inflater.inflate(R.layout.fragment_marque, container, false);
if (getArguments() != null) {
String mParam1 = getArguments().getString("edttext");
System.out.println("got this from MatchActivity "+mParam1);
}else{
System.out.println("got nothing");
}
}
I am not getting any arguments I don't know why.
Notice : am not getting an error am getting "got nothing" as output.
Change your code to this
Bundle bundle = new Bundle();
bundle.putString(edttext", "From Activity");
MarqueFragment fragobj = new MarqueFragment();
fragobj.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_marque, fragobj);
transaction.commit();
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");
}
}
I want to get search result from search bar which is in Activity and show all list in a fragment. How can I do it?
#Override
public boolean onQueryTextSubmit(String query) {
if (query.length() > 0) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment newFragment = new SearchFragment(); //your search fragment
Bundle args = new Bundle();
args.putString("query_string", query);
newFragment.setArguments(args);
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
return false;
}
Hope this will solve your issue ... Let me know in the comment ...(its just an example.. as you have not provided the sufficient information related your query)
Link
I searched your query and found above link ...
Edited:
Step 1: Passing the data from activity to fragment,
Bundle bundle = new Bundle();
bundle.putString("params", "My String data");
// set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);
Step 2: Receiving the data to the fragment,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("params");
}
}
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.
This question already has answers here:
How can I launch fragment in broadcast receiver
(3 answers)
Closed 7 years ago.
I want to open a fragment through a sms-receiver, how should I implement that? Any help is appreciated.
Receiver source code:
public class SMSReceiver extends BroadcastReceiver {
private String body, vsn;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null)
return;
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[i]);
body = sms.getMessageBody().toString();
PaymentTransaksi.setSmsDetail(body);
Intent showPaymentForm = new Intent();
showPaymentForm.setClassName("showPaymentForm",
"id.dutapulsa.bayartagihan.PaymentTransaksi");
showPaymentForm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
And this is the fragment source code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
paymentRootView = inflater.inflate(R.layout.payment_main, container,
false);
return paymentRootView;
}
I know this question is quite old, but I want to share my solution with the community because it is a common task.
1.) In your layout file (e.g. of your MainActivity) create a container, which will be replaced by the current fragment.
2.) Add the following code snippet to your Activity (don't forget to change it a bit, if neccessary)
public void updateFragment(Class<?> clazz, Bundle args) {
String tag = clazz.getName();
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
fragment = Fragment.instantiate(this, tag, args);
fragment.setRetainInstance(true);
}
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.addToBackStack(tag);
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
}
3.) Now you can simply call this method from your BroadcastReceiver, like this one:
updateFragment(ContentFragment.class, null);
4.) For dialogs I extend from DialogFragment and have the following method in my Activity:
public static void showProgressDialog(Activity activity, String title, String message) {
FragmentManager fragmentManager = activity.getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString(ProgressDialogFragment.ARG_TITLE, title);
bundle.putString(ProgressDialogFragment.ARG_MESSAGE, message);
ProgressDialogFragment mProgressDialog = new ProgressDialogFragment();
mProgressDialog.setArguments(bundle);
mProgressDialog.setRetainInstance(true);
mProgressDialog.show(fragmentManager, "Dialog");
}
Hope I can help! ;-)