I’m trying to launch context from android MainActivity class to flutter. code :
val authResult = ComponentActivity().registerForActivityResult(PianoIdAuthResultContract()) { r ->
when (r) {
null -> { /* user cancelled Authorization process */ }
is PianoIdAuthSuccessResult -> {
val token = r.token
val isNewUserRegistered = r.isNewUser
if (token != null) {
if (token.emailConfirmationRequired) {
// process enabled Double opt-in
}
}
// process successful authorization
}
is PianoIdAuthFailureResult -> {
val e = r.exception
// Authorization failed, check e.cause for details
}
}
}
and then calling the method launch code :
try{
authResult.launch(PianoId.signIn());
}catch (e : Exception){
val text = e.message
val duration = Toast.LENGTH_SHORT
val toast = Toast.makeText(applicationContext, text, duration)
toast.show()
}
and then I call this method from flutter by creating a channel between flutter and android and invoke it :
signInChannel.invokeMethod('testSignIn');
when I press the sign in button it shows me this exception :
Attempt to invoke virtual method ‘android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()’ on a null object reference
Advertisement
Answer
I too was searching for the solution. what i did was extend MainActivity with FlutterFragmentActivity and pass this to method channel handler.
public class MainActivity extends FlutterFragmentActivity{
...
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine)
{
handlePickerMethodChannel(flutterEngine);
}
private void handlePickerMethodChannel(FlutterEngine flutterEngine) {
PickerMethodChannelHandler PickerMethodChannelHandler = new PickerMethodChannelHandler(new WeakReference<>(this));
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), PHOTO_PICKER_METHOD_CHANNEL)
.setMethodCallHandler(pickerMethodChannelHandler);
}
}
class PickerMethodChannelHandler(
private val activity: WeakReference<Activity>,
) : MethodChannel.MethodCallHandler {
private val pickMedia = (activity.get() as ComponentActivity).registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
if (uri != null) {
Log.d("PhotoPicker", "Selected URI: $uri")
} else {
Log.d("PhotoPicker", "No media selected")
}
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"pickMedia" -> pickMedia(call,result)
else -> result.notImplemented()
}
}
private fun pickMedia(call: MethodCall, result: MethodChannel.Result) {
val context = activity.get() as ComponentActivity
Log.i("PICK_MEDIA","PICK ${context != null}")
pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo))
}
}
It worked