In my fragment, I am fetching a string from the web and I want the hosting activity to be enable to get this string and use it to set the subtitle of it's actionbar when the backstack changes. I follow this answer and is using the third option.
This are my codes:
Match Activity
public class Match extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener{
public String matchTitle
public String getMatchTitle() {
return matchTitle;
}
public void setMatchTitle(String matchTitle) {
this.matchTitle = matchTitle;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
//The usuals
if (savedInstanceState == null) {
Bundle bundle = new Bundle();
Fragment fragment;
fragment = new DetailsFragment();
bundle.putString("match_link", news_id);
fragment.setArguments(bundle);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.slide_in_left);
ft.add(R.id.match_frame, fragment);
ft.commit();
}
if (savedInstanceState != null) {
mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
}
}
....
@Override
public void onBackStackChanged() {
String subtitle = getMatchTitle();
mToolbar.setSubtitle(subtitle);
}
...
DetailsFragment
public class DetailsFragment extends Fragment {
public DetailsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView called");
//The usuals
}
private void getMatch() {
Log.d(TAG, "getMatch called");
String matchJson = GET_URL + matchID;
JsonObjectRequest matchDetails = new JsonObjectRequest(Method.GET, matchJson, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse for getMatch called");
parseJson(response);
mainMatch = response;
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getMatch called");
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
});
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(matchDetails);
}
private void parseJson(JSONObject object) {
Log.d(TAG, "Parsing Json");
try {
final String title = String.valueOf(Html.fromHtml(object.getString("title")));
matchTitle.setText(title);
Match match = new Match();
match.setMatchTitle(title);
} catch (JSONException w) {
w.printStackTrace();
}
}
NOTE I know I can easily set the subtitle from the fragment but I don't want to do that. I just want to make sure I can access a variable in a fragment from it's host activity.