Passing data from an activity to a fragment - android

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.

Related

Transfer data from one fragment to another fragment

I am developing an app in which I have used bottom navigation bar so for that I had to use fragments. In my fragments, I implemented Recycler view. So My question is when I click on an item of recycler view, how can I navigate to another fragment (which is in a different item of the bottom navigation bar) and how can I transfer the data between two fragments. Please Help.
during onClick() pass data through bundle
like that
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
Bundle bundleobj = new Bundle();
bundleobj.putCharSequence("key", data);
Fragment2 fragobj = new Fragment2();
fragobj.setArguments(bundleobj);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.containerView, fragobj).commit();
In Fragment2 class:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle =getArguments();
if(null!=bundle) {
myData=bundle.getCharSequence("key");
}
}
In first Fragment..
Fragment fragment = new EditExamFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Bundle bundle = new Bundle();
bundle.putString("branch_id", mDataset.get(position).getiBranchId());
bundle.putString("exam_id",mDataset.get(position).getiExamId());
fragment.setArguments(bundle);
In Second Fragment for fetching values try below code;
String branch_id, exam_id ;
final Bundle bundle = this.getArguments();
if (bundle != null) {
branch_id = bundle.getString("branch_id");
exam_id = bundle.getString("exam_id");
}
Add below code after event listener in fragment1
SecondFragmentName secondFragmentName = new SecondFragmentName();
Bundle args = new Bundle();
args.putString("key", "value");
secondFragmentName.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, secondFragmentName).addToBackStack("Some string").commit();
To get value in Fragment2
String message = getArguments().getString("key");

how fragment can get data from parentActivity?

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"); ...

Passing argument to fragment that is defined in XML layout

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?

Getting arguments from a bundle

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
}

Android passing object to fragment

I have a message class
class Message
{
public String message, sender;
public Message (String msg, String from)
{
message = msg;
sender = from;
}
public String toString () { return sender+":"+message; }
}
I defined a table variable for use this class in main activity:
Hashtable<String, ArrayList<Message>> table = new Hashtable<String, ArrayList<Message>>();
I am adding data in main activity to message class with this code:
table.put("user01", new ArrayList<Message>());
table.get("user01").add(new Message("message","sender"));
And I want to use this table variable in another fragment.I am passing with this code to fragment.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
fragmentTransaction.add(R.id.container, conv);
ConversationFragment frgObj=ConversationFragment.newInstance(table.get("user01"));
fragmentTransaction.replace(R.id.container, frgObj,"ConversationFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
And this is newInstance function in Conversation fragment
static int myData;
public static ConversationFragment newInstance(ArrayList<Message> _extractedMessages){
ConversationFragment fragment = new ConversationFragment();
myData=_extractedMessages.size();
return fragment;
}
But I am getting nullpointer exception,for _extractedMessages.size().
This code is working
System.out.println(_extractedMessages);
But this is not working
System.out.println(_extractedMessages.size());
Ps:I can use size function in main activity,I can't use only in conversation fragment.
How can I fix it ?
Typically you pass parameters to the fragment in the Bundle (and make sure the Message class implements Parcelable):
public static ConversationFragment newInstance(ArrayList<Message> _extractedMessages){
ConversationFragment fragment = new ConversationFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_MESSAGES, _extractedMessages);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myData = getArguments().getParcelable(KEY_MESSAGES);
}

Categories

Resources