Here's my code in
MainActivity.java
ViewFragment fr = new ViewFragment();
Bundle bundle = new Bundle();
String val="sonali";
bundle.putString("myname", val);
fr.setArguments(bundle);
return fr;
In my ViewFragment.java the code for retrieving data in onActivityCreated() is..
Bundle bundle = getArguments();
String val = bundle.getString("myname");
if (val == null) {
Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "text " + val , Toast.LENGTH_LONG).show();
}
It gives null. Can any one help me.
a) Activity -> Fragment
In your activity : create a bundle and use
fragment.setArguments(bundle)
in your fragment : use
Bundle bundle = getArguments()
2) fragment -> Activity
In your fragment : create un interface with getter and setter methods (callback methods)
In your activity : implement the interface
3) fragment -> Activity
In your activity : Create public getter and setter or other methods
In your fragment : called public activity getter, setter or other methods using :
getActivity().getSomething(), getActivity().setSomething(args) or getActivity().someMethod(args)
4) activity -> fragment
In your fragment : create a public method
In your activity : call an active fragment public method :
getSupportFragmentManager().findFragmentById(R.id.your_fragment).publicMethod(args)
You can also set a new instance metho for your fragment (I think it's the easiest way) and things as user name can be saved in usersettings (SharedPref).
static final ViewFragment newInstance(String myName) {
//TODO: Save myName
}}
I tried it & it works fine. In activity onCreate method add
Bundle bundle = new Bundle();
bundle.putString("my_key","my_value");
ViewFragment fg = new ViewFragment();
fg.setArguments(bundle);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, fg)
.commit();
}
In fragment on onActivityCreated add
Bundle bundle = getArguments();
String value = bundle.getString("my_key");
Toast.makeText(getActivity(),value,Toast.LENGTH_SHORT).show();
Related
Hi I'm learning now about Fragments and I have some doubts.
V1:
So the correct way to create a new Fragment should be with "newInstance" instead of a constructor and would be something like this:
Fragment fragment = MyFragment.newInstance(variable);
And the code on the class "MyFragment" should be this:
private static final String ARG_PARAM1 = "param1";
private int variable;
public MyFragment() {
//Empty constructor
}
New instance will receive the param and will put them on a Bundle and set the argument for the class
public static mi_fragment newInstance(Int param1) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
Then after setting it the method onCreate will pick up the argument:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
variable = getArguments().getInt(ARG_PARAM1);
}
V2:
But I still can't see the problem with using the constructor and setting the arguments programatically:
Bundle bundle = new Bundle();
bundle.putInt("key", variable);
Fragment fragment = new MyFragment();
fragment.setArguments(bundle);
Then I pick up the argument on the method onCreate:
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if(bundle!=null){
variable = getArguments().getInt("key");
}
}
So I decided to search on the internet about this and I found a good answer but I still can't seem to understand it or when you could use it.
the way to pass stuff to your Fragment so that they are available after a Fragment is recreated by Android is to pass a bundle to the setArguments method.
This Bundle will be available even if the Fragment is somehow recreated by Android.
So my conclusion is that you keep the bundle alive and using the newInstance could make you return to the last fragment for example. But probably I'm wrong so I need help.
Question: What's the main difference between both and how do you benefit from newInstance ? An example.
I am trying to get bundle extras from activity 1 to fragment of activity 2 but getargument() always returns as null.
//Using this to get string in fragment
String value = getArguments().getString("abc");
//activity1 code that i used to get the extras
Bundle bundle = new Bundle();
bundle.putString("abc", townextra);
UserFragment myFrag = new UserFragment();
myFrag.setArguments(bundle);
There is a problem with logic of passing data.
Correct way would be: Pass data from Activity1 to Activity2, and then from Activity2 to Fragment.
all fixed. I added a new function on my activity 2 to create fragment. instead of doing it in oncreat. it all works fine, thanks
Your Activity
Bundle bundle = new Bundle();
bundle.putString("params", "Your String data");
// set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);
The Fragment.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString("params");
}
}
But will be better if you show the code how you pass data between activities and then use my answer.
And please add your fragment code.
I have a problem with pass data from activity to fragment, it says null pointer exception, but my data is not null.
This is my activity :
#Override
public void onResponse(Call call, Response response) throws IOException {
dataj = response.body().string();
System.out.println(dataj);
Bundle bundle = new Bundle();
bundle.putString("datak", dataj);
FragmentUtama fu = new FragmentUtama();
fu.setArguments(bundle);
Intent load = new Intent(LoginActivity.this, MainActivity.class);
load.putExtra("datajs", dataj);
startActivity(load);
finish();
}
and this is my fragment :
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
String datas = getArguments().getString("datak");
System.out.println(datas);
return inflater.inflate(R.layout.fragment_utama, container, false);
}
Thanks for your help.
You don't pass data to fragment via Intents. Arguments are passed by setting them to the fragment instance before calling Fragment transaction commit.
SomeFragment f = new SomeFragment ();
// Supply data input as an argument.
Bundle args = new Bundle();
args.putInt("some_key", value);
f.setArguments(args);
then you read it in your fragment.
NOTE: setArguments can only be called before the Fragment is attached to the Activity. So if fragment is already attached, it will not transfer any data to the fragment.
Bundle args = getArguments();
int value = args.getInt("some_key", 0);
you may try this,
use findFragmentByTag it will help you to find fragment and send data over it.
FragmentUtama fu =(FragmentUtama)getSupportFragmentManager().findFragmentByTag(FragmentUtama.class.getSimpleName())
Bundle bundle = new Bundle();
bundle.putString("datak", dataj);
fu.setArguments(bundle);
or
you can have one setter method in fragment and set data from activity to fragment
from Activity.
fu.setData(dataj);
In fragment
String data;
public void setData(String data)
{
this.data=data;
}
use data using getter method of fragment
public String getData()
{
return data;
}
You need to pass the data to MainActivity using extras of an intent and then using setArguments to pass it to the fragment that belongs to this activity when replacing/adding that fragment to its container.
I've two activity "Name_Status" and "Main_activity".
In Main_activity , i've fragments . i wanna send a string value from Name_Status activity to one of Main_activity fragment.
Below is the method of Name_Status activity:
#Override
public void onClick(View v) {
if (v.getId() == R.id.ok_change_name)
{
name = name_change.getText().toString();
System.out.println(name);
Log.d("entered", "entred");
MainActivity obj=new MainActivity();
Log.d("obj created", "obj created");
obj.changeMainName(name);
Log.d("obj.changename", "obj.changename");
}
}
By using this method i'm first sending data to the Main_activity and from there sending data to fragment as below.
Below is the code of Main_activity:
public void changeMainName(String s) {
FragActivity1 obj = (FragActivity1) getSupportFragmentManager().findFragmentById(R.id.person_profile); obj.changeName(s);
}
Now from here I'm sending string value to fragment class and there I'm only setting the string to the textview like below:
public void changeName(String s)
{
Log.d("changename entry" ,"changename netry");
System.out.println(s);
System.out.println(name_field.getText().toString());
name_field.setText(s);
System.out.println(name_field.getText());
}
I'm getting
NullPointerException at obj.changeMainName(name);
You gonna have to do some relay. For instance you have activity A which has no Fragment and Activity B which has a fragment. On Android framework you can first pass data to From Activity A to B and From Activity B you can pass data to its Fragment following the view Hierarchy.
In Activity A. do the following
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("key", "value");
startActivity(intent);
Now inside Activity B, get data from activity A
String stringValue= getIntent().getStringExtra("key");
Then pass that data your Fragment as an argument before to start Frag
Bundle bundle = new Bundle();
bundle.putString("key", stringValue);
ActivityBFrag fragment = new ActivityBFrag();
fragment.setArguments(bundle);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(container, fragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
Then inside your Fragment class. get data like below whenever you wanna access your data, can be inside onCreate, OnActivityCreated etc.
public void getArguments(){
Bundle bundle = getArguments();
if(bundle != null){
String stringValue = bundle.get("key");
}
}
Send data to second activity by Intent bundle. Then get the data in second activity by getIntent().getExtras() and then pass the data to fragment.
I am currentley launching new activities and passing data liek this:
Intent myIntent = new Intent(c, TastePage.class);
myIntent.putExtra("taste", tempTaste);
c.startActivity(myIntent);
and then retrieving the data in the new activity with:
//get data from listview
Bundle extras = getIntent().getExtras();
String taste = extras.getString("taste");
In order to follow android design guidelines better I am implementing a navigation drawer and changing my activities into fragments. I am just a little confused on how to pass data between fragments.
For loading new fragments I am using this code:
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_two=new BPTopTastes();
tran.replace(R.id.main, Fragment_two);//tran.
tran.addToBackStack(null);
tran.commit();
what can I implement into that code to pass data to the new fragment, and how can I retrieve that data in the new fragment?
Use a bundle:
Send data from source fragment
Fragment fragment = new Fragment();
final Bundle bundle = new Bundle();
bundle.putString("user_name", myusername);
fragment.setArguments(bundle);
And read from target fragment
Bundle args = getArguments();
if (args != null && args.containsKey("user_name"))
String userName = args.getString("user_name");
It is not the best idea but you can also use setters to set some values. You don't have to use Bundle.
public class YourFragment extends Fragment{
private String mUserName;
public void setUserName(String userName) {
mUserName = userName;
}
}
......
FragmentTransaction tran = getSupportFragmentManager().beginTransaction();
YourFragment fragment = new YourFragment();
fragment.setUserName(myUserName);
tran.add(R.id.main, fragment, "frag");
tran.addToBackStack(null);
tran.commit();
you could use Singleton Class to pass information between any component on your android process
you could access them from your services / activities / fragments ....
for example
class GlobalVars{
private GlobalVars global;
private String taste;//generate get/set
public static GlobalVars getinstance(){
if(global==null){global = new GlobalVars();}
return global}}
}
//By Calling
GlobalVars.getinstance()
//you will have a common access to the variables inside the class