In my FragmentActivity I have a fragment. This fragment loads data from server. I want we user clicks on refresh button then I call a method in fragment and do refreshing process.
I created an interface in FragmentActivity and set its variable when user clicks on refresh button. The code is like this:
public class MainScreen extends FragmentActivity {
public interface OnRefreshSelected {
public void refreshFragment(boolean flag);
}
private OnRefreshSelected onRefreshSelected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Try to create MainScreen...");
setContentView(R.layout.activity_main);
onRefreshSelected = (OnRefreshSelected) MainScreen.this;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
onRefreshSelected.refreshFragment(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And in Fragment class i implemented this interface:
public class CategoryFragment extends Fragment implements OnRefreshSelected {
@Override
public void refreshFragment(boolean flag) {
Log.i(TAG, "refresh requested. Try to reload data for this fragment...");
getData();
}
}
When I run, the application crashes and logcat shows this message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.astro.recipe.activities/com.astro.recipe.activities.MainScreen}: java.lang.ClassCastException: com.astro.recipe.activities.MainScreen
and points to this line:
onRefreshSelected = (OnRefreshSelected) MainScreen.this;
What is the best way to have access to a method of fragment from its host? any suggestion would be appreciated. Thanks