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.
Related
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.
This might have already answered but I am still troubling with a function like this. Let's say I have activity A and activity B. B holds a viewpager with several fragments in it. I would like to call a function in the fragment held by activity B from activity A.
I used callbacks many times to communicate between activites and fragments but every single time it was only the fragment and its holder activity. I do not want to make a static method (the callback listener cannot be static anyway) so it causes a headache for me. The simple static solution to make a static method in the fragment and have it called from the other actually works very well, but I am not sure if it was a good idea as I need to change several things static.
So communicating between Activity B and its fragments is ok, but I cannot call this method in Activity A.
Activity B:
public class ActivityB extends FragmentActivity implements Fragment1.OnWhateverListener
{
...
#Override
public void onWhateverSelected(int position) {
//stuff, here I can call any function in Fragment 1
}
}
The following code snippet is a wrong solution (doesnt even work) but makes a better picture what I would like to do.
Activity A:
ActivityB ab = new ActivityB ();
ab.onWhateverSelected(number);
So how can I do this?
Thank you!
EDIT
Activity A: the method I call
Bundle args = new Bundle();
args.putString("ID", id); // the data to send
Intent frag_args = new Intent(Intent.ACTION_VIEW);
frag_args.setClass(this, MainActivity.class);
frag_args.putExtra("args", args);
startActivity(frag_args);
Activity B:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
...
processIntent(getIntent()); //last line of onCreate, always gets called here
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent); // this never gets called here only in OnCreate
}
private void processIntent(Intent intent) {
Bundle args = intent.getBundleExtra("args");
if (args != null) { // check if ActivityB is started to pass data to fragments
String id = args.getString("ID");
Log.i("ID_FROM", "id: " + id); //works well
if (id != null) {
List<Fragment> fragments = new ArrayList<Fragment>();
fragments = getSupportFragmentManager().getFragments();
//NULLPOINTER for the following line
FragmentMainDiscover fr = (FragmentMainDiscover) fragments.get(0);
fr.RefreshHoverView(id);
}
}
}
You are right to stay away from statics. Way too risky, for visual objects that may or may not be on screen.
I would recommend going through activity B, since it is the parent of your target fragment. Create an Intent that starts activity B, and include an intent extra that tells activity B what it should do to the target fragment. Then activity B can make sure that the fragment is showing, and pass the information on to it.
One other idea to pass the info to the fragment is to use setArguments, rather than direct calls. This is a nice approach because Android will restore the arguments automatically if the activity and its fragments are removed from memory.
Does this make sense? Do you want the code?
EDIT
To use arguments, you still need to have activity A go through activity B. This is because activity A doesn't know if activity B, and all its fragments, is running unless it sends it an Intent. But you can include data targeted for the fragments, by putting them inside the intent. Like this:
public class ActivityA extends Activity {
public static final String KEY_FRAG = "frag"; // tells activity which fragment gets the args
public static final String KEY_ARGS = "args";
public static final String KEY_MY_PROPERTY = "myProperty";
public void foo() {
Bundle args = new Bundle();
args.putString(KEY_FRAG, "frag1Tag"); // which fragment gets the data
args.putCharSequence(KEY_MY_PROPERTY, "someValue"); // the data to send
// Send data via an Intent, to make sure ActivityB is running
Intent frag_args = new Intent(Intent.ACTION_VIEW);
frag_args.setClass(this, ActivityB.class);
frag_args.putExtra(KEY_ARGS, args);
startActivity(frag_args);
}
}
public class ActivityB extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//TODO configure activity including fragments
processIntent(getIntent()); // this call is in case ActivityB was not yet running
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent); // this call is in case ActivityB was already running
}
private void processIntent(Intent intent) {
Bundle args = intent.getBundleExtra(ActivityA.KEY_ARGS);
if (args != null) { // check if ActivityB is started to pass data to fragments
String fragTag = args.getString(ActivityA.KEY_FRAG);
if (fragTag != null) {
Fragment frag = getSupportFragmentManager().findFragmentByTag(fragTag);
frag.setArguments(args);
//TODO either show the fragment, or call a method on it to let it know it has new arguments
}
}
}
}
public class Fragment1 extends Fragment {
public static final String TAG = "frag1Tag";
#Override
public void onResume() {
super.onResume();
Bundle args = getArguments();
String value = args.getString(ActivityA.KEY_MY_PROPERTY);
...
}
}
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();
I have two Activities (A and B) and a Fragment F
The Fragment F is contained in the Activity B
I'd like to send Strings from Activity A to Fragment F
How can do that?
Thanks!
It is Almost same as you would exchange data between activities. you should just use getActivity() in the beginning in order to access in fragments.
check below code:
In Activity A:
Intent intent = new Intent(this,ActivityB.class);
intent.putExtra("data",data); //data is a string variable holding some value.
startActivity(intent);
In fragment F of Activity B
String data = getActivity().getIntent().getStringExtra("data");
First, you'll actually send that string to your activity B. For example:
Intent intent = new Intent(this, YourActivityClass.class);
intent.putExtra("myString", "this is your string");
startActivity(intent);
then later read that string from your activity B and inject into your fragment before executing the fragment-transaction. For example:
Bundle args = new Bundle();
args.putString("myString", getIntent().getExtras().getString("myString"))
yourFragment.setArguments(args);
Later, use getArguments() in your fragment to retrieve that bundle.
Or alternatively, use the following in your fragment to directly access the activity intent and fetch your required value:
String str = getActivity().getIntent().getStringExtra("myString");
For more info, read this.
In Fragment.java file add the following code,
public static String name= null;
public void setName(String string){
name = string;
}
In MainActivity.java from which you want to send String add the following code,
String stringYouWantToSend;
Fragment fragment = new Fragment();
fragment.setName(stringYouWantToSend);