arleitiss
arleitiss

Reputation: 1304

Android: Can't set TextView value in fragment

so I started using fragments today and I am trying to set TextView values on fragment opening. Values can be changed so I packed it all into 1 function so it can be called to update data. Here:

public void loadDetails(){
    ShortcutFunc sf = new ShortcutFunc(this.getActivity());
    ConversePrefs cp = new ConversePrefs(this.getActivity());
    sf.setTextValue(getActivity(), R.id.profile_name, cp.GetStringSetting("name", "unset") + " " + cp.GetStringSetting("surname", "unset"));
    String dob = cp.GetStringSetting("dob", "unset");
    String bod[] = dob.split("\\-");

    LocalDate birthdate = new LocalDate (Integer.valueOf(bod[2]), Integer.valueOf(bod[1]), Integer.valueOf(bod[0]));
    LocalDate now = new LocalDate();
    Years age = Years.yearsBetween(birthdate, now);
    sf.setTextValue(getActivity(), R.id.profile_bd, dob + " (" + String.valueOf(age) + ")");
    sf.setTextValue(this.getActivity(), R.id.profile_country, cp.GetStringSetting("country", "unset").toString());
    sf.setTextValue(this.getActivity(), R.id.profile_email, cp.GetStringSetting("email", "unset").toString());

    String joined[] = cp.GetStringSetting("join", "unset").split("\\s+");
    String joinedArray[] = joined[0].split("\\-");

    LocalDate joindate = new LocalDate(Integer.valueOf(joinedArray[0]), Integer.valueOf(joinedArray[1]), Integer.valueOf(joinedArray[2]));
    LocalDate today = new LocalDate();
    //Years joinedThen = Years.yearsBetween(joindate, today);
    Days joinedThen = Days.daysBetween(joindate, today);

    sf.setTextValue(this.getActivity(), R.id.profile_join, joined[0] + " (" + joinedThen.toString() + " Days)");
    sf.setTextValue(this.getActivity(), R.id.profile_user, cp.GetStringSetting("username", "unset").toString());
}

ShortcutFunc contains this function:

public void setTextValue(Activity act, int id, String text){
    TextView tv = (TextView)act.findViewById(id);
    tv.setText(text);
}

I use it to save time and set TextViews without doing all that declare etc.. I get NullPointerException on tv.setText(text) the ShortcutFunc function.

This is how I call loadDetails():

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadDetails();
    }

So what's wrong?

Upvotes: 1

Views: 278

Answers (1)

Ahmed Hegazy
Ahmed Hegazy

Reputation: 12605

These TextViews are members of your Fragment not the Activity that is holding the Fragment. You should initialize them from the view that you inflated for you fragment in theOnCreateView() method

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.my_view, container, false);
        textView = (TextView) view.findViewById(R.id.my_text_view);
        return view;
}

Upvotes: 1

Related Questions