Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use method onNewIntent(Intent intent) inside a Fragment?

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!

like image 728
Vinícius Mendes de Souza Avatar asked May 05 '15 02:05

Vinícius Mendes de Souza


People also ask

How do you get onNewIntent in 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.

How do I start an intent from activity to 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 .

What are fragment in android?

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.


2 Answers

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());
    }

}
like image 58
inmyth Avatar answered Oct 06 '22 17:10

inmyth


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
    }
}
like image 38
Hasan El-Hefnawy Avatar answered Oct 06 '22 15:10

Hasan El-Hefnawy