Set Fragment EditText from the parent Activty - android

I have a ProfileFragment class which contains two setters:
public void setPseudo(String pseudo){
textPseudo.setText(pseudo);
}
public void setEmail(String email){
textEmail.setText(email);
}
And in my Activity I would like to call these functions:
user = new ProfileFragment();
if (intent != null) {
user.setPseudo(intent.getStringExtra(USER_PSEUDO));
user.setEmail(intent.getStringExtra(USER_EMAIL));
}
It says "can't resolve method...".
Does it mean I can't do this?

Are you sure you don't have a Profile class with setters? Not a Fragment?
Fragments generally don't use setters, they use arguments.
Reason being: If you call setEmail, and then you called to some view setText within the new Fragment, you get a NullPointerException because that TextView was never initialized
Fragment profileFragment = new ProfileFragment();
Bundle args = new Bundle();
if (intent != null) {
args.putAll(intent.getExtras());
}
profileFragment.setArguments(args);
// Show new Fragment
getSupportFragmentManager()
.replace(R.id.content, profileFragment)
.commit();
And inside your Fragment's onCreateView, you can now use this, for example
final Bundle args = getArguments();
String pseudo = "";
if (args != null) {
pseudo = args.getString(YourActivity.USER_PSEUDO);
}
textPseudo.setText(pseudo);

Related

How to send Data from Fragment to other Fragment inside FirebaseAdapter, using model.class to getPid

i have being trying to solve this problem for while thought, i'm trying to pass the data from Fragment to other Fragment, the model.getPid suggesting me to be static!, and after running the app and clicking on the image then the app crachs!
thanks in advance!
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductsDetailsFragment fragment = new ProductsDetailsFragment();
Bundle b1 = new Bundle();
b1.putString("pid", Products.getPid());
fragment.setArguments(b1);
FragmentManager fragmentManager =
getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.nav_host_fragment, fragment)
.addToBackStack(null)
.commit();
this is from the second Fragment
Bundle bundle = this.getArguments();
if (bundle != null) {
productID= bundle.getString("pid");
getProductDetails(productID);
}
in the FirebaseAdapter when i pass the ProductTD, it returns null
private void getProductDetails(String productID) {
DatabaseReference productRef = FirebaseDatabase.getInstance().getReference().child("Products");
productRef.child(productID).addValueEventListener(new ValueEventListener() {
#Override
this is from Logcat
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
here is your error Intent intent = new Intent(getActivity(), ProductsDetailsFragment.class);
intent.putExtra("pid", model.getPid());
startActivity(intent)
remove this you can use intent for fragment

changing fragment's textview from activity does not update UI

I am attempting to do something that seems common practive (f.i. here, second answer). But while the data is transmitted and can be put f.i. into a viewmodel, android does not seem to care that I have changed the text of a textview. This is my code (I prefer databinding over findviewbyid):
Activity:
#Override
public void onItemSelected(String param) {
MainFragment oFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag(MainFragmentTag);
if(oFragment != null) {
oFragment.SetText(param);
getSupportFragmentManager()
.beginTransaction()
.replace(oBinding.mainContainer.getId(), oFragment)
.addToBackStack(null)
.commit();
}
}
Receiving Fragment:
public void SetText(String param) {
String sInput = oBinding.MyInputField.getText().toString();
oBinding.TextviewIWantToChange.setText(param);
Entry oEntry = Manager.CreateEntry(sInput, param);
viewmodel.Insert(oEntry);
}
The old fragment instance shows up, the right param is transmitted and viewmodel insertion works smoothely. But the textview is not updated. Any ideas?
Pass your data with Fragment arguments and read another fragment getArguments
#Override
public void onItemSelected(String param) {
MainFragment oFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag(MainFragmentTag);
if(oFragment != null) {
Bundle bundle=new Bundle();
bundle.putString("param",param);
oFragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(oBinding.mainContainer.getId(), oFragment)
.addToBackStack(null)
.commit();
}
}
// Call this on which fragment you have need
public void SetText(String param) {
String sInput = oBinding.MyInputField.getText().toString();
oBinding.TextviewIWantToChange.setText(param);
Entry oEntry = Manager.CreateEntry(sInput, param);
viewmodel.Insert(oEntry);
}
Call thi methhod on OnCreateView
final Bundle bundle = getArguments();
String param = bundle.getString("param");

How can i pass adapter to fragment like in intent

I am new to android and I am trying to call my MapFragment from adapter after on click using intent below is my code
Below is adapter code:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final BusInfo info = getItem(position);
View view = LayoutInflater.from(context).inflate(R.layout.bus_only_list,null);
TextView busname;
busname = (TextView) view.findViewById(R.id.busname);
busname.setText(info.name);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = context.getSharedPreferences("busInfo",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("bus_name",info.name);
editor.commit();
Intent intent = new Intent(context, MapsFragment.class);
intent.putExtra("name",info.name);
context.startActivity(intent);>
}
});
return view;
}
I want to pass to mapfragment using intent but it redirect to MainActivity instead of MapFragment. How can I stop transferring to MainActivity?
Thank you.
A common pattern to passing a value to a Fragment is using newInstance method. In this method you can set Argument to fragment as a means to send the value.
First, create the newInstance method:
public class YourFragment extends Fragment {
...
// Creates a new fragment with bus_name
public static YourFragment newInstance(String busName) {
YourFragment yourFragment = new YourFragment();
Bundle args = new Bundle();
args.putString("bus_name", busName);
yourFragment.setArguments(args);
return yourFragment;
}
...
}
Then you can get the value in onCreate:
public class YourFragment extends Fragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the value from arguments
String busName = getArguments().getString("bus_name", "");
}
...
}
You can set the value to the Fragment from your activity with:
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
YourFragment yourFragment = YourFragment.newInstance("bus_name_value");
fragTransaction.replace(R.id.fragment_place_holder, yourFragment);
fragTransaction.commit();
You can use the above codes to send the value in Fragment initialization.
If you want to set the value to the already instantiated fragment, you can create a method then invoke the method to set the value:
public class YourFragment extends Fragment {
...
public setBusName(String busName) {
// set the bus name to your fragment.
}
...
}
Now, In the activity, you can invoke it with:
// R.id.yourFragment is the id of fragment in xml
YourFragment yourFragment = (YourFragment) getSupportFragmentManager()
.findFragmentById(R.id.yourFragment);
yourFragment.setBusName("bus_name_value");
You cannot pass an intent to a Fragment. Try using a Bundle instead.
Bundle bundle = new Bundle();
bundle.putString("name", info.name);
mapFragment.setArguments(bundle)
In your Fragment (MapsFragment) get the Bundle like this:
Bundle bundle = this.getArguments();
if(bundle != null){
String infoName = bundle.getString("name");
}
As guys mentioned before:
1. Use callback or just casting on your context (your activity must handle changing fragments itself).
2. To change fragments use activity's FragmentManager - intent is used to start another activity.
Fragments Documentation

Create an interface to communicate with another fragment

I created an interface so I can set text on a FragmentB when I press a TextView on FragmentA. Something is not working and I can't figure this out.
I've created an interface called Communicator:
public interface Communicator {
void respond(String data);
}
On FragmentA I've set a reference on the interface called Communcator and an OnClickListener on the TextView:
Communicator comm;
homeTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comm.respond("Trying to set text on FragmentB from here");
}
});
FragmentB, set my method to change text:
public void setText(final String data) {
startTripTxt.setText(data);
}
Finally in MainActivity I've implemented the interface .. I think here is where I'm doing something wrong:
#Override
public void respond(String data) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_main, new FragmentB(), "fragment2").addToBackStack(null).commit();
FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2");
if (fragmentB != null) {
fragmentB.setText(data);
}
}
Fragment 2 loads, but the text is empty.
Fragment 2 loads, but the text is empty.
You implement Communicator is ok but the way you call FragmentB and passing data is not ok. That 's is the reason why you cannot get text from FragmentB. the right way to send data to FragmentB should be like this:
public static FragmentB createInstance(String data) {
FragmentB fragment = new FragmentB();
Bundle bundle = new Bundle();
bundle.putString("data", data);
fragment.setArguments(bundle);
return fragment;
}
And you can get data from FragmentB by:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
It looks like after you declare fragmentB, you're meaning to set the text on that fragment. You are Instead calling trainFinderFragment.setText(). Is that your issue?
FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2");
if (fragmentB != null) {
fragmentB.setText(data);
}

How to add fragment on activity in android? [duplicate]

This question already has answers here:
Start a fragment via Intent within a Fragment
(5 answers)
Closed 6 years ago.
i want to replace activity to a fragment, this code is not working.
Intent intent = new Intent(Activity.this, Fragment.class);
startActivity(intent);
finish();
You cannot switch from an Activity to Fragment, because a Fragment does not have its own existence without an Activity. i.e. a Fragment works inside an Activity.
Basically, Fragments are mainly used to create multi-pane screens.
Inside an Activity if you can replace Fragments (associated with the Activity) as mentioned in the above code examples to change the UI.
Try like this in your activity
#Override
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.flContent, fragment);
transaction.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();
}
and use like this
YourFragment mYourFrag = new YourFragment ();
replaceFragment(mYourFrag , false);
Create a Fragmen class like
public class FragmentName extends android.support.v4.app.Fragment {}
And then you are able to cast a activity to view like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View returner = null;
Intent intent = new Intent([CONTEXT],[CLASSNAME.class]);
Bundle args = this.getArguments();
final Window w = [LocalActivityManager].startActivity("Title", intent);
final View wd = w != null ? w.getDecorView() : null;
if (wd != null) {
ViewParent parent = wd.getParent();
if(parent != null) {
ViewGroup v = (ViewGroup)parent;
v.removeView(wd);
}
wd.setVisibility(View.VISIBLE);
wd.setFocusableInTouchMode(true);
if(wd instanceof ViewGroup) {
((ViewGroup) wd).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
}
returner = wd;
return returner;
}

Categories

Resources