I am trying to get my data from Activity to Fragment but couldn't be able to do it ı think there is a problem about requestCodes and resultCodes but o couln't find it. I made a little research but the answers didn't help me.
My companion objects in the fragment
companion object {
const val REQUEST_PERMISSION = 1001
const val REQUEST_MULTIPLE_PERMISSION = 1002
const val REQUEST_TO_POST = 1003
}
Fragment to activity
view.testButton.setOnClickListener {
val intent = Intent (activity, ReaderActivity::class.java)
startActivityForResult(intent,101)
}
Activity to fragment
card_results = result;
Log.d(TAG, "ResultActivity data is :" result);
Intent returnIntent = new Intent();
returnIntent.putExtra("cardResult", card_results );
setResult(Activity.RESULT_OK, returnIntent);
finish();
Fragment functions to handle data
private fun getDataFromNFC(intent: Intent){
Log.d(TAG, "getDataFromNFC: start")
try {
val result:String = intent.getStringExtra("cardResult").toString()
Log.d(TAG, "getDataFromNFC data is : $result")
}catch (e: NullPointerException){
Log.d(TAG, "error: $e")
Toast.makeText(activity,"Add a card",Toast.LENGTH_SHORT).show()
}
Log.d(TAG, "getDataFromNFC: ends")
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "onActivityResult: start")
if (requestCode == 101) {
when (requestCode) {
REQUEST_PERMISSION -> {
if (data != null) {
getDataFromNFC(data)
}
}
REQUEST_MULTIPLE_PERMISSION -> {
// Do something if success / failed
}
REQUEST_TO_POST -> {
// Parse result and do something
}
}
}
super.onActivityResult(requestCode, resultCode, data)
Log.d(TAG, "onActivityResult: ends")
}
CodePudding user response:
The only request code you are using is 101 when you use this code: startActivityForResult(intent,101)
.
Then in onActivityResult
, you first check if the request code is 101, which is fine, but then you have a when(requestCode)
block that does stuff only if the request code is not 101, which will never be true for any of those cases, especially inside an if-block that already guaranteed that the request code is 101.
Also, it should be noted that startActivityForResult()
is now deprecated in favor of Activity Result APIs.