I'm trying to use NFC Hardware from my device. But, the problem is that when I register the Activity to receive the Intent:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
I receive the result in an Activity instead of a Fragment. Is there a way to handle this result inside a Fragment?
Thanks in advance!
onNewIntent belongs to Activity so you cannot have it in your fragment. What you can do is pass the data to your fragment when it arrives in onNewIntent provided you have the reference to the fragment.
If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .
A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.
onNewIntent
belongs to Activity so you cannot have it in your fragment. What you can do is pass the data to your fragment when it arrives in onNewIntent
provided you have the reference to the fragment.
Fragment fragment;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Check if the fragment is an instance of the right fragment
if (fragment instanceof MyNFCFragment) {
MyNFCFragment my = (MyNFCFragment) fragment;
// Pass intent or its data to the fragment's method
my.processNFC(intent.getStringExtra());
}
}
I fixed my issue the following way:
in MyActivity.java
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
in MyFragment.java
@Override
public void onStart() {
super.onStart();
if (getActivity() != null && getActivity().getIntent().hasExtra(...)) {
// do whatever needed
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With