How To Get The Result From Onactivityresult Inside Another Class?(outside Of The Activity
Solution 1:
I know this is an old question but with the help of new api its simple:
myActivity.registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
doSomeOperations()
}
}.launch(yourIntent)
Solution 2:
I want to be able toget the result back inside the same classandnotin the activity.
No can do, you really cant get the result without executing your activity because startActivityForResult
is bounded with your activity when the other activity is finished.
solution:
Since you have your myActivity
in your another class you can use the Intent
from it to get the result from another activity in your class where you started the VoiceRecognition
. Also make sure that you call it after the VoiceRecognition
activity is finished.
sample:
myActivity.getIntent().getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Solution 3:
If I understand the question, you are trying to do something like this:
Sometimes it is useful to create a utility class that encapsulates custom code (in this case voice-related). The utility class is just a bunch of static
methods:
publicstaticclassVoiceRecognitionUtils {
privatestaticvoidstartVoiceRecognitionActivity(Activity myActivity) {
// TODO Auto-generated method stubIntentintent=newIntent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Talk");
myActivity.startActivityForResult(intent, REQUEST_CODE);
}
privatestaticvoidprocessResult(int requestCode, int resultCode, Intent data) {
for (final EditText editText : editTextHandlingList) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> results = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
}
}
}
}
Given that class your activity can just call the static methods from the appropriate lifecycle events:
publicclassMainActivityextendsFragmentActivity {
// ...protectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
VoiceRecognitionUtils.processResult(requestCode, resultCode, data);
}
// call startVoiceRecognitionActivity() somewhere
}
The voice recognition is still being started and the results received by the Activity
(because Android OS requires that), but the technical details are collected in the utility class.
I'm not certain from your question if this is what you were trying to do, but I would recommend this technique anyways, it's very useful.
Post a Comment for "How To Get The Result From Onactivityresult Inside Another Class?(outside Of The Activity"