Home Ask Login Register

Developers Planet

Your answer is one click away!

tasgr86 February 2016

fragment callback using interface

I have an Activity that starts a Fragment. 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 interface 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) {


  // called when user presses a button and MainActivity finishes.

public void doneListener(View v){
    // Here i get NULL


    public void onCommentEntered(String data) {
             // Here i get what the user typed

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 (){

public void onAttach(Context context) {


Nithinjith February 2016

Create a new Interface, as well as implement the same in Fragment. create a method in the interface and override the same in Fragments. While calling the fragment from Activity create an Interface type fragment and call the interface method.


 public class thefragment extends Fragment implement fragmentNofyInterface {
   protected void notify(String txt){

Interface Format

public interface fragmentNofyInterface {
     protected void notify(String txt);

Activity format

class MainActivity implements fragment.commentListener{  
       private fragmentNofyInterface mFragmentNotifier;


       thefragment  mFragment = new  thefragment();  
       mFragmentNotifier = (fragmentNofyInterface ) mFragment;
       FragmentTransaction transaction = mFragmentMngr.beginTransaction().
       transaction .commit();


      //Notify the fragment when you required

      mFragmentNotifier.notify("hello world"); 


tasgr86 February 2016

Switching to addTextChangedListener and TextWatcher for my EditText, like this here, seems to fix my problem.Now onCommentEntered method is called before doneListener and thus String commentgets whatever was typed in the EditText.Thanks everyone for helping.

Post Status

Asked in February 2016
Viewed 2,675 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life