open other app on button click from android appwidgetprovider [duplicate] - android-appwidget

How can i start a new application using its package name? I don't have information about what activity is the main one.

Just use these following two lines, so you can launch any installed application whose package name is known:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc");
startActivity( launchIntent );
If you don't know the package name of application that you wanted to launch then try your hand on:
PackageManager pm;
pm = getPackageManager();
// get a list of installed apps.
packages = pm.getInstalledApplications(0);
For more information, refer to this link: Using Package Manager.

Try using PackageManager and getLaunchIntentForPackage()

You can get the launch intent through the PackageManager class:
PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.example.package");
context.startActivity(launchIntent);
Note that getLaunchIntentForPackage returns null if the package isn't found. So you might want to add a null check:
if (launchIntent != null) {
context.startActivity(launchIntent);
} else {
Toast.makeText(context, "Package not found", Toast.LENGTH_SHORT).show();
}

Intent intent;
PackageManager pm = getActivity().getPackageManager();
intent = pm.getLaunchIntentForPackage("com.package.name");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Intent intent = getPackageManager().getLaunchIntentForPackage("app.package.name");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (intent != null) {
startActivity(intent);
} else {
Toast.makeText(context, "Package not found", Toast.LENGTH_SHORT).show();
}

val packageName = "com.google.android.youtube"
var intent = activity!!.packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
if (intent == null) {
intent = try {
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))
} catch (e: Exception) {
Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName"))
}
}
startActivity(intent)
For Android 11 (API level 30) or higher, in AndroidManifest.xml,
<queries>
<package android:name="com.google.android.youtube" />
<package android:name="com.example.app" />
</queries>
Or simply we can allow for all packages (not recommended)
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />
References
Package visibility filtering on Android

Related

AndroidStudio Kotlin connect to bluetooth

I've added <uses-permission android:name="android.permission.BLUETOOTH" /> to my manifest but the error
Missing permission required by BluetoothAdapter.isEnabled: android.permission.BLUETOOTH.
is still there.
Also, in ContextCompat.checkSelfPermission(...) what is the first parameter CONTEXT? The documentation https://developer.android.com/training/permissions/requesting does not say.
And am I correct that I need to disconnect and reconnect bluetooth whenever the app is not being used?
class MainActivity : AppCompatActivity() {
var bt: BluetoothAdapter? = null
var bts: BluetoothSocket? = null
val REQUEST_BLUETOOTH_PERMISSION: Int = 1
val REQUEST_BLUETOOTH_ENABLE: Int = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
{
Toast.makeText(
getApplicationContext(),
"Device does not support Bluetooth therefore this application cannot run.",
Toast.LENGTH_SHORT
).show();
return;
}
bt = BluetoothAdapter.getDefaultAdapter()
if (bt == null) {
// This device does not have Bluetooth.
Toast.makeText(
getApplicationContext(),
"Device does not have a Bluetooth adapter therefore this application cannot run.",
Toast.LENGTH_SHORT
).show();
return;
}
bluetoothConnect();
}
fun bluetoothConnect() {
if (ContextCompat.checkSelfPermission(
CONTEXT, // What is this? It's not explained at https://developer.android.com/training/permissions/requesting
Manifest.permission.BLUETOOTH
) == PackageManager.PERMISSION_GRANTED
) {
if (bt.isEnabled == false) { // Error: Missing permission required by BluetoothAdapter.isEnabled: android.permission.BLUETOOTH.
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_BLUETOOTH_ENABLE)
} else {
val pairedDevices: Set<BluetoothDevice>? = bt.bondedDevices
pairedDevices?.forEach { device ->
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
}
}
}
else {
// Request permission. That will call back to onActivityResult which in the case of success will call this method again.
// Ask for permission.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.BLUETOOTH),
REQUEST_BLUETOOTH_PERMISSION
)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_BLUETOOTH_PERMISSION) {
if (resultCode == RESULT_OK) {
bluetoothConnect();
} else {
Toast.makeText(
getApplicationContext(),
"This application cannot run because it does not have Bluetooth permission.",
Toast.LENGTH_SHORT
).show();
// Do we need to quit? How?
}
}
else if( requestCode == REQUEST_BLUETOOTH_ENABLE)
{
if(resultCode == RESULT_OK)
{
// try again
bluetoothConnect();
}
else {
Toast.makeText(
getApplicationContext(),
"This application cannot run because Bluetooth is not enabled and could not be enabled.",
Toast.LENGTH_SHORT
).show();
// Do we need to quit? How?
}
}
}
override fun onPause() {
super.onPause()
// Release Bluetooth
}
override fun onResume() {
super.onResume()
// Connect Bluetooth
}
override fun onStop() {
super.onStop()
// Release Bluetooth
}
override fun onStart() {
super.onStart()
// Connect Bluetooth
}
}
Edit:
added additional BT check to code,
adding manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rwb.btconnectortest">
<uses-permission android:name="android.permission.BLUETOOTH" />
<!--<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />-->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/btconnectortestTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Just because comments are not good for this, let me give you a list of things you ought to do before you can act with Bluetooth. (apologies this is in Java because that's what I have right now, but very easy to translate to Kotlin if needed)
I'm doing this for BT LE (low energy) which is the preferred way for.. obvious reasons.
Did you add the permission(s) to the Manifest? You need something like
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
Make sure Bluetooth exists and is turned on...
// Does BLE exist?
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
final BluetoothManager manager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
Now that you have a manager, you need to get the BluetoothAdapter:
BluetoothAdapter bluetoothAdapter = manager.getAdapter();
All this is fine in onCreate, but keep in mind that you have to check if BT is enabled every time the user resumes the activity (For it could have been turned off/disabled/revoked/etc).
Likely in onResume:
// obviously, you need to check that Bt adapter isn't null and all that,
// otherwise you ought to go back and "construct" it again, check permissions, etc.
adapter = getBTAdapter(); // do all the checks in there...
boolean bluetoothEnabled = adapter != null && adapter.isEnabled();
If the BT radio is off (user turning it off), you can programmatically enable it, if you have the corresponding permission (which I think is BT admin or similar, you're gonna have to search on that one, because it's been a while).
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> I believe it was.
Since BT is a radio that needs power, it will take a while (seconds) to turn on and be available. For this you need to "listen" with Yet Another broadcast receiver...
In other words, the activity will fire an intent (startActivityForResult(...)) telling Android to enable BT, you will subscribe to that broadcast to listen to the callback. Once android informs you that BT is on, you can go back to step 1 and start checking if it's enabled, you have permission, etc.
The callback is if I have not forgotten too much... looked like
public void onReceive(Context context, Intent intent) {
In there you ought to check for various BluetoothAdapter states... among them:
BluetoothAdapter.ACTION_STATE_CHANGED
This signals that the state changed, but another nested if is needed to determine to what state...
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE);
switch (state) {
case BluetoothAdapter.STATE_OFF:
case BluetoothAdapter.STATE_TURNING_OFF:
case BluetoothAdapter.STATE_TURNING_ON:
case BluetoothAdapter.STATE_ON:
}
Those are all the ones you care (check the BluetoothAdapter enum for more info).
In the ON you know BT is on... so..
Now you can tell the adapter that you want to scan...
adapter.startLeScan(callback);
(remember to call stopLeScan(callback) when you're done).
As each device is found, the callback will be called with the info you need to attempt to connect and pair (if needed).
The signature of the callback (LeScanCallback) is something like:
public void onScan(final BluetoothDevice device, int rssi, byte[] record);
(I'm typing by memory, so it may be a different name but you get the idea)
This is, as far as I can remember the old API.
API 21 has a ScanSettings.Builder() where you can specify how you want to scan, but it's essentially a similar method. Initiate scan, pass a callback and wait for results to show up.
You have various modes too:
SCAN_MODE_BALANCED: Balance battery efficiency and scan speed
SCAN_MODE_LOW_LATENCY: Prefer scan speed over battery
SCAN_MODE_LOW_POWER: Prefer battery efficiency over scan speed
SCAN_MODE_OPPORTUNISTIC: can't remember :) I think it was to use other scanner results 'around' you. Never used it.
Once you have identified the device you were looking for the BluetoothDevice has everything you need to tell BT to "connect" to it.
public void onScanResult(int callbackType, ScanResult scanResult) {
^ this is the signature of the "new" Scanner.
From that ScanResult, you can do:
int rssi = result.getRssi();
BluetoothDevice device = result.getDevice();
String advertiseName = device.getName();
String macAddress = device.getAddress();
If the scan fails for any reason, you get a callback on onScanFailed(int errorCode).
And again, there are various "reasons" (check the errorCode) why the scan failed.
Remember I may be mixing API 18 or API 21 "apis" here, but the concept is very similar in both.
Once you have finally grabbed a Device's MAC address... you can ask the adapter to try to connect to it:
BluetoothDevice device = adapter.getRemoteDevice(macAddress);
device.connectGatt(context, false, anotherCallback);
The callback is of BluetoothGattCallback and again, it has a bunch of methods among them onConnectionStateChange...
At this point you ought to read more about how Bluetooth works (and how it works on Android) because there are various modes (Gatt being one way) of operating with BT. It's impossible to know each and how/what you want to do once connected.
The rule of thumb will be: make sure you're prepared to having to re-pair or re-request permissions, because it's ultimately the user's choice to disable, turn off, walk-away, revoke permission, etc. at any point during this.
Good luck!
in manifest file add these two permission
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"
#########################################################
*NOTE:i attached my bluetooth kotlin code , and its work with me. I enter code herehope this helpful
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var myBluetooth:BluetoothAdapter? = null
lateinit var mypairedDevices:Set<BluetoothDevice>
val Request_Enable_Blutooth=1
companion object {
val EXTRA_ADDRESS :String= "Device_Address"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
myBluetooth= BluetoothAdapter.getDefaultAdapter()
if (myBluetooth == null)
{
Toast.makeText(applicationContext, "Bluetooth Device Not Available", Toast.LENGTH_LONG).show()
}
if (!myBluetooth!!.isEnabled)
{
val enableBlutoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBlutoothIntent, Request_Enable_Blutooth)
}
binding.BTNPairedDevices.setOnClickListener {
pairedDeviceList()
}
}
private fun pairedDeviceList (){
mypairedDevices = myBluetooth!!.bondedDevices
val list : ArrayList<BluetoothDevice> = ArrayList()
if (!mypairedDevices.isEmpty())
{
for ( device:BluetoothDevice in mypairedDevices)
list.add(device)
//list.add(device.name() + "\n" + device.address())
Log.i("Device", "This is messeage")
}
else {
Toast.makeText(applicationContext, " NO PAIRED DEVICES FOUND", Toast.LENGTH_LONG).show()
}
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
binding.DeviceListView.adapter = adapter
binding.DeviceListView.onItemClickListener = AdapterView.OnItemClickListener{ _, _, position, _ ->
val device: BluetoothDevice = list[position]
val address: String = device.address
val intent = Intent(this, LedController::class.java)
intent.putExtra(EXTRA_ADDRESS, address)
startActivity(intent)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Request_Enable_Blutooth)
{
if(resultCode ==Activity.RESULT_OK)
{
if (myBluetooth!!.isEnabled)
{ Toast.makeText(applicationContext, "Bluetooth Enabled", Toast.LENGTH_LONG).show()
}
else ( Toast.makeText(applicationContext, "Bluetooth Disabled", Toast.LENGTH_LONG).show()
)
}
} else if(resultCode == Activity.RESULT_CANCELED)
Toast.makeText(applicationContext, "Bluetooth has been canceled", Toast.LENGTH_LONG).show()
}
}
I restarted AndroidStudio and now the error has disappeared. What a complete piece of rubbish.
But now the layout is broken...

Connecting to MariaDB from an Android app

Disclaimer: I know people don't typically do this, I am using an SQL database for cost reasons, also I am relatively new to programming.
I am trying to send SQL scripts to my MariaDB database from my Android Studio application. I am currently working to implement a Java Database Connectivity (JDBC) driver for MariaDB however I'm not sure what I need to include.
I went to the download website for the JDBC MariaDB driver however there are many jar files which I have the option of downloading. How do you know which one you need and how do you know how to install it/where for Android? (https://downloads.mariadb.org/connector-java/2.3.0/)
As a note, my Java code is as follows, for which I get the error message "No suitable driver found for .... ":
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
}
else {
// Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
String host = "jdbc:mariadb://HOST:PORT/DBNAME";
String username = "UNAME";
String password ="PWD";
try {
Connection con = DriverManager.getConnection( host, username, password );
Toast.makeText(this, result.getContents() + " - Success!", Toast.LENGTH_LONG).show();
} catch (Exception err) {
Toast.makeText(this, err.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
You need to make sure to use the correct driver (connector). Download it and then you import it into Android Studio (libs folder) and then add the following to your app build gradle:
implementation files('libs/mariadb-java-client-1.8.0.jar')
This is the Connector/J that I use (V1.8.0) ... the newer ones don't seem to be compatible. Sample code:
// Create a connection
val myConn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/DB?user=username&password=myPassword")
Class.forName("org.mariadb.jdbc.Driver") // Initialize it
// Now you create SQL statements
val sql01 : PreparedStatement? = (myConn!!.prepareStatement(getString(R.string.sql01)))
// Submit the query
reset = sql01.executeQuery()

How to open a new activity when recycler view with search filter from hain file suggested some text is clicked in android studio

I want to open a new activity when search filter is clicked in recycler view of android studio.
An open source code may be found here that is given below. It has json file from where we can fetch the search filter item.
https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/
Please tell me the code that how we can get to new activity such as hello.xml when hello is being clicked in search filter item.
In my opinion the code should be here in mainactivity.java..
#Override
public void onContactSelected(Contact contact) {
String type = contact.getClass().getName();
if (type.startsWith("Tom")) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
} else if (type.startsWith("")) {
Intent intent = new Intent(MainActivity.this, Hello.class);
startActivity(intent);
}
Please help to put my code instead of toast.
public void onContactSelected(Contact contact) {
// TextView name = (TextView) Contact;
if ( contact.getName().toString().equalsIgnoreCase("Tom Hardy"))
{
startActivity(new Intent(MainActivity.this, Hello.class));
finish();
}
else{
Toast.makeText(MainActivity.this, " no activity "+contact.getName(), Toast.LENGTH_SHORT).show();
}
}

Error while processing request in AzureMobile Apps HTTP2 error

This question is specific to a lately strange behavior of the Azure mobile Apps Android sdk. Everything was working fine for weeks. Now, my android client app suddenly can't connect to my web app any more. A Toast says "Error while processing request". In Android Studio debugger, I found the exception inside the SDK file MobileServiceConnection.java.
java.io.IOException: stream was reset: PROTOCOL_ERROR
In Azure Portal, my app shows "Healthy" status, but I can see the HTTP errors. Please help.
Following is my code, which was working fine and now throws error.
// Create the Mobile Service Client instance, using the provided mobile app URL.
try {
mClient = new MobileServiceClient(mMobileBackendUrl, activityContext).withFilter(
new ServiceFilter() {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilter) {
// Get the request contents
String url = request.getUrl();
String content = request.getContent();
if (url != null) {
Log.d("Request URL:", url);
}
if (content != null) {
Log.d("Request Content:", content);
}
// Execute the next service filter in the chain
ListenableFuture<ServiceFilterResponse> responseFuture = nextServiceFilter.onNext(request);
Futures.addCallback(responseFuture, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable exception) {
Log.d("Exception:", exception.getMessage());
}
#Override
public void onSuccess(ServiceFilterResponse response) {
if (response != null && response.getContent() != null) {
Log.d("Response Content:", response.getContent());
}
}
});
return responseFuture;
}
}
);
setAzureClient(mClient);
}catch(MalformedURLException e){
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}catch(Exception e){
createAndShowDialog("There was an error creating the Mobile Service. "+ e.toString(), "Error");
}
Toast.makeText(context, context.getString(R.string.online_authentication), Toast.LENGTH_SHORT).show();
authenticate();
}
private void authenticate() { // give access only to authenticated users via Google account authentication
HashMap<String, String> parameters = new HashMap<>();
parameters.put("access_type", "offline");//use "Refresh tokens"
//login with the Google provider. This will create a call to onActivityResult() method inside the context Activity, which will then call the onActivityResult() below.
mClient.login(MobileServiceAuthenticationProvider.Google, url_scheme_of_your_app, GOOGLE_LOGIN_REQUEST_CODE, parameters);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When request completes
if (requestCode == 1) {
try {
MobileServiceActivityResult result = mClient.onActivityResult(data);
if (result.isLoggedIn()) {
Toast.makeText(context, context.getString(R.string.azure_auth_login_success) /*+ " " + mClient.getCurrentUser().getUserId()*/, Toast.LENGTH_SHORT).show();
mUserId = mClient.getCurrentUser().getUserId();
} else {//>>>>THIS IS WHERE I AM GETTING THE ERROR
String errorMessage = result.getErrorMessage();
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();// Error While processing request (it comes form the MobileServiceConnection.java file inside sdk)
}
}catch(Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
I found the answer myself. The error was due to an Azure App Service HTTP2 connection issue. It has nothing to do with the app code. For anyone facing the same problem, here is the solution.
Go to https://resources.azure.com/
Make sure you are in Read/Write mode by clicking in the option to the left of your name.
From the left column, browse to: https://resources.azure.com/subscriptions/yourSubscriptionId/resourceGroups/yourWebAppResourceGroup/providers/Microsoft.Web/sites/yourWebAppName/config/web
Find and Change the property: "http20Enabled": from true to false by clicking EDIT, Update value to “false” and then clicking in Save or PATCH.

onActivityResult not called in Fragment

In my fragment onActivityResult is not calling after startActivityForResult .As i have tried following things:
1) adding getParentFragment , getActivity before startActivityResult
2) added on manifest android:configChanges="orientation|screenSize"
3)onActivityResult is not being called in Fragment
4)Checked finish () method in ZbarScanner Activity
Intent dataIntent = new Intent();
dataIntent.putExtra(SCAN_RESULT, symData);
dataIntent.putExtra(SCAN_RESULT_TYPE, sym.getType());
setResult(Activity.RESULT_OK, dataIntent);
finish();
5) Error- [ResultInfo{who=null, request=196609, result=-1, data=Intent { (has extras) }}]} checked intent has value not null which we are passing
if (isCameraAvailable()) {
Intent intent = new Intent(this.getActivity(), ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, 1);
Toast.makeText(getActivity(), "inside case", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
----onActivityResult------
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bundle bundle = data.getExtras();
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == getActivity().RESULT_OK) {
Toast.makeText(getActivity(), "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == getActivity().RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}}
I called onActivityResult on MainActivity and with this its not calling .so removed switch case .and its working now
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
It is very common and known issue for fragment onActivityResult. I have solved it in one way, there might be other ways also.
set tag when you are moving to Fragment from Activity like this.
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment,"tag").commit();
now write below code in your onActivityResult of Activity.
if (requestCode == 1) { //set your requestcode whichever you are using
//super.onActivityResult(requestCode, resultCode, data);
//dont forget to comment this.
Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag("tag");
if(fragment != null){
fragment.onActivityResult(requestCode, resultCode, data);
}
}
I had a similar issue while working with a FragmentPagerAdapter inside a Fragment. The problem was that I initialized my PagerAdapter with the Fragment's FragmentManager, I replaced:
new MyPagerAdapter(getChildFragmentManager());
with
new MyPagerAdapter(getFragmentManager());
So it might be worth checking which FragmentManager you are using. I'm not 100% happy with this approach yet as it seems right to call the Fragment's FragmentManager. But I did not get the time to check it any further yet.

Resources