简体   繁体   中英

Does this situation cause Memory Leak?

I am writing an android project, I write these code, I want to know if my code will cause some memory leak.

As you will see I set "OnItemSelectedListener" in FoldActivity, then I implement the "ItemSelectedListener" in FoldFragment, so the fragment always monitor the listener, I am worried about that when a fragment is replaced, can the fragment retrieve by gc?

I think the fragment always has a reference from foldActivity which cause gc can never retrieve it even it has been replaced by some other fragment.

public class FolderActivity extends Activity {
    // ...

    Spinner spinner;

    protected void onCreate(Bundle savedInstanceState) {
        // ...
        final View spinnerView = inflater.inflater(R.layout.category_spinner, null);
        spinner = spinnerView.findViewById(R.id.categorySpinner);

        // ...
    }

    protected void onPostCreate(Bundle savedInstanceState) {
        // ...
        if (getFragmentManager.findFragmentById(R.id.fragment) == null) {
            Fragment folderFragment = new folderFragment();
            if (getIntent().hasExtra(EXTRA_DIR)) {
                Bundle args = new Bundle();
                args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
                    folderFragment.setArguments(args);
            }
        }

        showFragment(folderFragment);
    }

    public void showFragment(Fragment fragment) {
        spinner.setOnItemSelectedListener((folderFragment)fragment);
        getFragmentManager()
            .beginTransaction()
            .addToBackStack(null)
            .replace(R.id.fragment, fragment)
            .commit();
    }
}


public class FoldFragment extends Fragment implements AdapterView.OnItemSelectedListener {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Log.d(LOG_TAG, "item selected");
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        Log.d(LOG_TAG, "nothing selected");
    }
}

You don't have to worry about leaking the reference by adding the fragment as a listener via the setOnItemSelectedListener method. As you can see in the source , this method overwrites the reference to the original listener, which will remove the reference. This is a nice aspect of the android api design: setting a listener rather than adding one, as is typical in Swing, for example, is much less likely to cause a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM