trying to set up a custom listener to send a string from an Activity to a fragment that is inside of that activity. button on Activity is pressed and the String of text should be sent to the fragment and displayed in the textview of that fragment but I get a classCastException and don't know what to do about this. how would you get this to work?
the error is on this line
listener = (OnStringRequestedListener) fragment;
i don't know how to set up this custom listener interface without that line of code. i used a similar line of code for going in the opposite direction and it worked. that was or sending a message from fragment to Activity. however what i am trying today is not working
stack trace
Caused by: java.lang.ClassCastException:
com.example.asynctaskprogressbarexample.InterfaceActivityToFragmentFragment
cannot be cast to com.example.asynctaskprogressbarexample
.InterfaceActivityToFragment$OnStringRequestedListener
at com.example.asynctaskprogressbarexample
.InterfaceActivityToFragment.onCreate(InterfaceActivityToFragment.java:27)
activity class
public class InterfaceActivityToFragment extends Activity {
Button buttonOne;
private OnStringRequestedListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.interface_activity_to_fragment);
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment1);
listener = (OnStringRequestedListener) fragment; // <-- ERROR ON THIS LINE
if (fragment instanceof OnStringRequestedListener) {
listener = (OnStringRequestedListener) fragment;
} else {
throw new ClassCastException(fragment.toString()
+ " must implemenet OnTimeRequestedListener");
}
buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
listener.passString("string from Activity");
}
});
}
public interface OnStringRequestedListener {
public void passString(String sendNumberString);
}
}
fragment class
public class InterfaceActivityToFragmentFragment extends Fragment implements FragmentHeadlessAsyncTaskFragment.OnStringRequestedListener {
TextView textViewOne;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.interface_activity_to_fragment_fragment, container, false);
TextView textViewOne = (TextView) view.findViewById(R.id.textView1);
return view;
} // end on create view
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
@Override
public void passString(String stringFromActivity) {
textViewOne.setText(stringFromActivity);
}
}