how to pass string from activity to fragment? - android

Activity A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ActivityA);
Bundle b = new Bundle();
b.putString("mobile", "123456789");
FragmentA fragmentA = new FragmentA ();
fragmentA .setArguments(b);}
FragmentA
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragmentA, container, false);
String txtMobile = getArguments().getString("mobile");
Log.i("mobile2",txtMobile);
mobile.setText(txtMobile);}
I have tried above solution but showing error that
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

May be It's about the way you are adding fragment to the class:
Bundle b = new Bundle();
b.putString("mobile", "123456789");
FragmentA fragmentA = new FragmentA ();
fragmentA .setArguments(b);
fm.beginTransaction()
.replace(placeholder, new FragmentA(), tabId)
.commit();
can you provide more data about how did you add it ?

Create your fragment like this
public static MyFragment newInstance(String string) {
Bundle args = new Bundle();
args.putString("string",string);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
And then in Fragment onCreate use getArguments() for pulling that String. Don't forget to check getArguments() for null.

Try to fetch the argument in onCreate method of fragment with default value constructor:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String txtMobile = getArguments().getString("mobile", "");
}
and make sure you commit the fragment transaction after settting the arguments in fragment. :)

First check that your argument is not null.
For example
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragmentA, container, false);
if(getArguments()!=null){
String txtMobile = getArguments().getString("mobile");
Log.i("mobile2",txtMobile);
mobile.setText(txtMobile);
}
}

try this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null){
String txtMobile = savedInstanceState.getString("mobile");
}
}

you can use inteface to pass data from activity to fragment
In your activity
public interface FragmentRefreshListener {
void onRefresh(String mydata);
}
public FragmentRefreshListener fragmentRefreshListener;
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
Then inside your fragment add below code
((MainActivity) getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh(String mydata) {
// write your logic here
}
});
use following in your activity to pass data from activity to fragment
getFragmentRefreshListener().onRefresh("dummy text");

Related

How to get view of a newly created fragment from recyclerview adapter?

holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileFragment myFragment = new ProfileFragment();
ProfileFragment.profileFragment.getFragmentManager().beginTransaction().replace(R.id.RelLayout1, myFragment).addToBackStack(null).commit();
Log.d(TAG, "onClick: rr");
}
});
This is called inside a Recyclerview Adapter.On clicking an item ,I want to create a new instance of the fragment and hide some of the views inside the created Fragment.
You can send flag on fragment arguments and check this flag on the fragment class
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileFragment myFragment = new ProfileFragment();
Bundle fragmentBundle = new Bundle();
fragmentBundle.putBoolean(ProfileFragment.MY_FLAG, true);
myFragment.setArguments(fragmentBundle);
ProfileFragment.profileFragment.getFragmentManager().beginTransaction().replace(R.id.RelLayout1, myFragment).addToBackStack(null).commit();
}
});
And now you can check this flag in your fragment class
public class ProfileFragment extends Fragment{
public static final String MY_FLAG = "MY_FLAG";
private boolean hideShowFlag = false;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check if arguments not null and contains the desired key
//if all true set value to a variable to be used later
if (getArguments() != null && getArguments().containsKey(MY_FLAG) {
this.hideShowFlag = getArguments().getBoolean(MY_FLAG);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mView = inflater.inflate(getRootView(), container, false);
if (this.hideShowFlag) {
//write your logic for show and hide here
}
return mView;
}
}
hope my answer will help you.

Inflating fragment through a fragment and passing arguments

I was trying to inflate a same fragment through a fragment and passing arguments, its working but the arguments which are passed are applied on the previous fragment but not on the new fragment.
The fragment contains a TextView and a Spinner.
fragment class:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.myfragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle b = getArguments();
qust = b.getString("Question","");
id = b.getInt("id");
final connection con = (connection) getActivity();
question = (TextView) getActivity().findViewById(R.id.question);
spinner = (Spinner) getActivity().findViewById(R.id.spinner);
question.setText(qust);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),id,R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (i!=0)
con.inflate();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
I am inflating a fragment when the user selects any item in the previous fragment spinner.
MainActivity class:
public class MainActivity extends AppCompatActivity implements connection {
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragments mF = new MyFragments();
Bundle b = new Bundle();
b.putString("Question","Where are you?");
b.putInt("id",R.array.planets_array);
mF.setArguments(b);
FragmentManager manage = getFragmentManager();
FragmentTransaction trans = manage.beginTransaction();
trans.add(R.id.root,mF,"frag");
trans.commit();
}
#Override
public void inflate() {
MyFragments f = new MyFragments();
Bundle b = new Bundle();
b.putString("Question","what are you doing?");
b.putInt("id",R.array.colours);
f.setArguments(b);
FragmentTransaction tran = getFragmentManager().beginTransaction();
tran.add(R.id.root,f,"added");
tran.commit();
}
}
interface to communicate b/w fragments:
public interface connection {
void inflate();
}
screenshot
I think that has been occurred, because you instantiate new fragment on
your inflate() method without unique TAG. Set up unique TAG or use different add(#IdRes int containerViewId, Fragment fragment) instead.

Android create fragment with Arguments not work

I want to create fragment with Arguments,
and refer to this post [ Do fragments really need an empty constructor? ].
But not work, I don't know how to fix it.
Code:
Fragment
public class TestFragment extends Fragment {
private final static String BUNDLE_TITLE = "title";
private RelativeLayout rootView;
private String title = "";
public static TestFragment newInstance(String titleName){
Bundle bundle = new Bundle();
bundle.putString(BUNDLE_TITLE,titleName);
TestFragment testFragment = new TestFragment();
testFragment.setArguments(bundle);
return testFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
if (rootView == null) {
rootView = (RelativeLayout) inflater.inflate(R.layout.find_mac, container, false);
}
return rootView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
if(data != null){
this.title = getArguments().getString(BUNDLE_TITLE,"");
}
}
String getTitle() {
return title;
}
}
And in Activity,
#Override
protected void onStart() {
super.onStart();
TestFragment testFragment = TestFragment.newInstance("hello");
Log.d("debug","get title:"+testFragment.getTitle());
}
The Log show only "get title:",
I can't get the title "hello" word.
This is because when you calling:
TestFragment testFragment = TestFragment.newInstance("hello");
Log.d("debug","get title:"+testFragment.getTitle());
the testFragment fragment is not yet finished created. Because it is an asynchronous process.
So, you need to create a listener in activity to tell that the fragment is created, then in it, you can get the title.
You can read Communicating with Other Fragments for implementing the listener.

Passing data from an Activity to a fragment that has no onCreate

Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate
Try this one
public class SampleActivity extends AppCompactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
if (savedInstanceState == null) {
Fragment fragment = new SampleFragment();
Bundle args = new Bundle();
args.putInt("sample_int", 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
}
}
}
public class SampleFragment extends Fragment {
#Override
public void onResume() {
Bundle args = getArguments();
if (args != null) {
int sampleInt = args.getInt("sample_int", -1);
}
}
}
From Activity, you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// 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 strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

pass data to Fragment

I have an Activity and a simple fragment ,I try to use Bundle to pass data to the fragment, but the bundle is always null.
I can't figure out what is the problem?!
this is my Activity class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragmentA =new FragmentA();
Bundle bundle=new Bundle();
bundle.putString("name","Ahmed Ezzat");
fragmentA.setArguments(bundle);
}
public void showFragment(View view) {
FragmentA fragmentA=new FragmentA();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragmentA,"fragment A");
transaction.commit();
}
}
and this is my fragment class
public class FragmentA extends Fragment {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
textView= (TextView) view.findViewById(R.id.tv_fragment);
Bundle bundle = this.getArguments();
String name = bundle.getString("name");
if (name!=null){
textView.setText(name);}
return view;
}
}
any help?
You never called setArguments in the showFragment method.
The Fragment in the onCreate method is never used.
You may try using the following code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showFragment(View view) {
FragmentA fragmentA=new FragmentA();
Bundle bundle=new Bundle();
bundle.putString("name","Ahmed Ezzat");
fragmentA.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.dumper,fragmentA,"fragment A")
.commit();
}
}
You can pass data to the fragment when building the fragment, then passing it to the transaction.
public class FragmentA extends Fragment {
TextView textView;
String message;
public FragmentA(String message){
this.message = message;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
textView= (TextView) view.findViewById(R.id.tv_fragment);
textView.setText(message);
return view;
}
And when attaching, you just pass it in the constructor.

Categories

Resources