I have an Activity
that starts a Fragmen
t. Inside that fragment i have an EditText
. And when i get the text that the user types there, i want to get that from my Activity
with the help of an interface
. I'm using this guide
On my MainActivity
i'm implementing the commentListener interfac
e and i've managed to get the result inside the onCommentEntered
method. But on doneListener
, which is triggered when the user presses a button finishing the activity, i'm getting null.
Obviously onCommentEntered
runs after doneListener
.
Any suggestions on how to get the result on doneListener
?
class MainActivity implements fragment.commentListener{
static String comment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addtransaction);
done=(TextView)findViewById(R.id.done_button);
}
// called when user presses a button and MainActivity finishes.
public void doneListener(View v){
// Here i get NULL
System.out.println(comment);
finish();
}
@Override
public void onCommentEntered(String data) {
comment=data;
// Here i get what the user typed
System.out.println(comment);
}
}
My fragment
public class thefragment extends Fragment {
commentListener cListener;
static TextView note;
EditText comment;
public interface commentListener{
void onCommentEntered(String data);
}
public static thefragment newInstance(){
return new thefragment ();
}
public thefragment (){
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
cListener=(commentListener) context;
}
@Override
public void onDetach() {
super.onDetach();
cListener=null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
v=inflater.inflate(R.layout.fragment, container, false);
comment=(EditText)v.findViewById(R.id.comment_picker);
comment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
cListener.onCommentEntered(comment.getText().toString());
}
}
});
return v;
}
}