I want to change the text of my TextView
element, which is defined in the corresponding QuoteFragment.class
file and the related layout.xml
file. You can see the code of the method in my main activity:
private void forwardToQuoteFragment(Quote quote){
quoteFragment = QuoteFragment.newInstance(quote);
View view = quoteFragment.getView();
TextView tv = (TextView) view.findViewById(R.id.quoteFragmentHeader);
tv.setText("Quote (" + quote.getId() + "): " + quote.getQuote());
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, quoteFragment);
ft.commit();
}
My debugger tells me, that the view variable is null, therefore I got an NPE. It will make no difference, if I created the view-property in my QuoteFragment.class
, which you can see below:
public class QuoteFragment extends android.support.v4.app.Fragment {
public static final String QUOTE_FRAGMENT_TAG = "QuoteFragment";
public static final String QUOTE_ID = "quoteId";
private View view;
private long quoteId;
public QuoteFragment(){
// required
}
// factory to set arguments
public static QuoteFragment newInstance(Quote quote) {
QuoteFragment fragment = new QuoteFragment();
Bundle args = new Bundle();
args.putLong(QUOTE_ID, quote.getId());
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context){
super.onAttach(context);
Log.i(QUOTE_FRAGMENT_TAG, "onAttach()");
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.i(QUOTE_FRAGMENT_TAG, "onCreate()");
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.fragment_quote, container, false);
return view;
}
public void setQuoteId(long id){
this.quoteId = id;
}
public long getQuoteId() {
return quoteId;
}
public View getView(){
return this.view;
}
}
What is the best way to solve this issue? What did I overlooked?