1.

I want to pass a String value from one Fragment to another fragment How to do this?

Answer»

In, we can send information from one activity to another and vice-versa using startActivityForResult() method. The android startActivityForResult method requires a result from the second activity. For that, we need to override the onActivityResult method that is invoked automatically when the second activity returns a result.

public void startActivityForResult (Intent intent, int requestCode)

Now we will see how to send data from Activity B back to Activity A?

  • In Activity A we will call explicit Intent in NEXT Button click, this will call Intent and it will call ActivityB.
intentActivityD = new Intent(…);    intentActivityD;    startActivityForResult(intentActivityD, SOME_REQUEST_CODE)

In Activity B we will send someResultCode to Activity  A, which will HANDLE it with the onActivityResult and send it back again with setResult(…) finish();

goBackToActivityA(){    setResult(someResultCode);    finish(); }
  • Once it received result from Activity B it will call method onActivityResult. Which will then know by the flag that the activity B no LONGER exists, hence the activity that should handle it is Activity A, which means the resultCode will finally arrive in the onActivityResultCode of Activity A.
override FUN onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {        // check if the requestCode is the WANTED one and if the result is what we are expecting        if (requestCode == REQUEST_FORM && resultCode == RESULT_OK) {            val name = data?.getStringExtra(FormActivity.INPUT_NAME)            addItemToList(name) // do something with the value        }    }


Discussion

No Comment Found

Related InterviewSolutions