-1

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Baptiste Arnaud
  • 2,522
  • 3
  • 25
  • 55

1 Answers1

2

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);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Right, you need to statically import it – OneCricketeer Apr 08 '17 at 20:49
  • You declared it in another Activity is the exact reason that you need to either import it, or qualify it, as I have in my updated answer – OneCricketeer Apr 08 '17 at 20:55
  • I tried this in the new Activity : public static final String USER_PSEUDO = ""; it says it's already defined in scope ... I don't understand. – Baptiste Arnaud Apr 08 '17 at 20:57
  • Without seeing your full code, all I can say is check your import statements – OneCricketeer Apr 08 '17 at 20:58
  • Seriously passing variables from Activities to Fragments is this complicated....? I'm totally lost here – Baptiste Arnaud Apr 08 '17 at 21:04
  • Lost with what? It's not that complicated. http://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment Fragments are designed to be isolated elements from the Activity. If you really need an updatable view, then you want a custom `View` class, not a Fragment. – OneCricketeer Apr 08 '17 at 21:11